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
attentiveness/News
app/src/main/java/org/attentiveness/news/detail/StoryDetailContract.java
// Path: app/src/main/java/org/attentiveness/news/base/BasePresenter.java // public interface BasePresenter { // // void subscribe(); // // void unsubscribe(); // // } // // Path: app/src/main/java/org/attentiveness/news/base/BaseView.java // public interface BaseView<T> { // // void setPresenter(@NonNull T presenter); // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import org.attentiveness.news.base.BasePresenter; import org.attentiveness.news.base.BaseView; import org.attentiveness.news.data.StoryDetail;
package org.attentiveness.news.detail; interface StoryDetailContract { interface View extends BaseView<Presenter> {
// Path: app/src/main/java/org/attentiveness/news/base/BasePresenter.java // public interface BasePresenter { // // void subscribe(); // // void unsubscribe(); // // } // // Path: app/src/main/java/org/attentiveness/news/base/BaseView.java // public interface BaseView<T> { // // void setPresenter(@NonNull T presenter); // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/detail/StoryDetailContract.java import org.attentiveness.news.base.BasePresenter; import org.attentiveness.news.base.BaseView; import org.attentiveness.news.data.StoryDetail; package org.attentiveness.news.detail; interface StoryDetailContract { interface View extends BaseView<Presenter> {
void showStoryDetail(StoryDetail storyDetail);
attentiveness/News
app/src/main/java/org/attentiveness/news/detail/StoryDetailContract.java
// Path: app/src/main/java/org/attentiveness/news/base/BasePresenter.java // public interface BasePresenter { // // void subscribe(); // // void unsubscribe(); // // } // // Path: app/src/main/java/org/attentiveness/news/base/BaseView.java // public interface BaseView<T> { // // void setPresenter(@NonNull T presenter); // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import org.attentiveness.news.base.BasePresenter; import org.attentiveness.news.base.BaseView; import org.attentiveness.news.data.StoryDetail;
package org.attentiveness.news.detail; interface StoryDetailContract { interface View extends BaseView<Presenter> { void showStoryDetail(StoryDetail storyDetail); void showError(String message); boolean isActive(); }
// Path: app/src/main/java/org/attentiveness/news/base/BasePresenter.java // public interface BasePresenter { // // void subscribe(); // // void unsubscribe(); // // } // // Path: app/src/main/java/org/attentiveness/news/base/BaseView.java // public interface BaseView<T> { // // void setPresenter(@NonNull T presenter); // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/detail/StoryDetailContract.java import org.attentiveness.news.base.BasePresenter; import org.attentiveness.news.base.BaseView; import org.attentiveness.news.data.StoryDetail; package org.attentiveness.news.detail; interface StoryDetailContract { interface View extends BaseView<Presenter> { void showStoryDetail(StoryDetail storyDetail); void showError(String message); boolean isActive(); }
interface Presenter extends BasePresenter {
attentiveness/News
app/src/main/java/org/attentiveness/news/detail/StoryDetailFragment.java
// Path: app/src/main/java/org/attentiveness/news/base/BaseFragment.java // public class BaseFragment extends Fragment { // // public BaseFragment() { // // Required empty public constructor // } // // protected void showMessage(View anchorView, String message) { // Snackbar.make(anchorView, message, Snackbar.LENGTH_SHORT).show(); // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.FrameLayout; import org.attentiveness.news.R; import org.attentiveness.news.base.BaseFragment; import org.attentiveness.news.data.StoryDetail; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
WebSettings webSettings = this.mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); setHasOptionsMenu(true); return view; } @Override public void setPresenter(@NonNull StoryDetailContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void onResume() { super.onResume(); this.mPresenter.subscribe(); } @Override public void onPause() { super.onPause(); this.mPresenter.unsubscribe(); } @Override public void showError(String message) { this.showMessage(this.mRootView, message); } @Override
// Path: app/src/main/java/org/attentiveness/news/base/BaseFragment.java // public class BaseFragment extends Fragment { // // public BaseFragment() { // // Required empty public constructor // } // // protected void showMessage(View anchorView, String message) { // Snackbar.make(anchorView, message, Snackbar.LENGTH_SHORT).show(); // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/detail/StoryDetailFragment.java import android.annotation.SuppressLint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.FrameLayout; import org.attentiveness.news.R; import org.attentiveness.news.base.BaseFragment; import org.attentiveness.news.data.StoryDetail; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; WebSettings webSettings = this.mWebView.getSettings(); webSettings.setJavaScriptEnabled(true); setHasOptionsMenu(true); return view; } @Override public void setPresenter(@NonNull StoryDetailContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void onResume() { super.onResume(); this.mPresenter.subscribe(); } @Override public void onPause() { super.onPause(); this.mPresenter.unsubscribe(); } @Override public void showError(String message) { this.showMessage(this.mRootView, message); } @Override
public void showStoryDetail(StoryDetail storyDetail) {
attentiveness/News
app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.List; import io.reactivex.Observable;
package org.attentiveness.news.data.source; public interface StoriesDataSource { Observable<List<Story>> getStories(String date);
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.List; import io.reactivex.Observable; package org.attentiveness.news.data.source; public interface StoriesDataSource { Observable<List<Story>> getStories(String date);
Observable<StoryDetail> getStoryDetail(int storyId);
attentiveness/News
app/src/main/java/org/attentiveness/news/list/StoryListAdapter.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.attentiveness.news.R; import org.attentiveness.news.data.Story; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package org.attentiveness.news.list; class StoryListAdapter extends RecyclerView.Adapter<StoryListAdapter.ViewHolder> { interface OnItemClickListener {
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // Path: app/src/main/java/org/attentiveness/news/list/StoryListAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; import org.attentiveness.news.R; import org.attentiveness.news.data.Story; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package org.attentiveness.news.list; class StoryListAdapter extends RecyclerView.Adapter<StoryListAdapter.ViewHolder> { interface OnItemClickListener {
void onStoryClicked(Story story);
attentiveness/News
app/src/main/java/org/attentiveness/news/data/source/local/LocalStoriesDataSource.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java // public interface StoriesDataSource { // // Observable<List<Story>> getStories(String date); // // Observable<StoryDetail> getStoryDetail(int storyId); // // void saveStories(@NonNull List<Story> storyList); // // void refreshStories(); // // void deleteAllStories(); // // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.data.source.StoriesDataSource; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable;
package org.attentiveness.news.data.source.local; public class LocalStoriesDataSource implements StoriesDataSource { private static LocalStoriesDataSource INSTANCE; private StoriesDbHelper mDbHelper; // Prevent direct instantiation. private LocalStoriesDataSource(@NonNull Context context) { this.mDbHelper = new StoriesDbHelper(context); } public static LocalStoriesDataSource getInstance(@NonNull Context context) { if (INSTANCE == null) { INSTANCE = new LocalStoriesDataSource(context); } return INSTANCE; } @Override
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java // public interface StoriesDataSource { // // Observable<List<Story>> getStories(String date); // // Observable<StoryDetail> getStoryDetail(int storyId); // // void saveStories(@NonNull List<Story> storyList); // // void refreshStories(); // // void deleteAllStories(); // // } // Path: app/src/main/java/org/attentiveness/news/data/source/local/LocalStoriesDataSource.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.data.source.StoriesDataSource; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; package org.attentiveness.news.data.source.local; public class LocalStoriesDataSource implements StoriesDataSource { private static LocalStoriesDataSource INSTANCE; private StoriesDbHelper mDbHelper; // Prevent direct instantiation. private LocalStoriesDataSource(@NonNull Context context) { this.mDbHelper = new StoriesDbHelper(context); } public static LocalStoriesDataSource getInstance(@NonNull Context context) { if (INSTANCE == null) { INSTANCE = new LocalStoriesDataSource(context); } return INSTANCE; } @Override
public Observable<List<Story>> getStories(String date) {
attentiveness/News
app/src/main/java/org/attentiveness/news/data/source/local/LocalStoriesDataSource.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java // public interface StoriesDataSource { // // Observable<List<Story>> getStories(String date); // // Observable<StoryDetail> getStoryDetail(int storyId); // // void saveStories(@NonNull List<Story> storyList); // // void refreshStories(); // // void deleteAllStories(); // // }
import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.data.source.StoriesDataSource; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable;
} @Override public Observable<List<Story>> getStories(String date) { List<Story> storyList = new ArrayList<>(); SQLiteDatabase database = this.mDbHelper.getReadableDatabase(); String[] projections = { StoriesPersistenceContract.StoryEntry.COLUMN_NAME_STORY_ID, StoriesPersistenceContract.StoryEntry.COLUMN_NAME_TITLE}; Cursor cursor = database.query(StoriesPersistenceContract.StoryEntry.TABLE_NAME, projections, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { while (cursor.moveToNext()) { int storyId = cursor.getInt(cursor.getColumnIndexOrThrow(StoriesPersistenceContract.StoryEntry.COLUMN_NAME_STORY_ID)); String title = cursor.getString(cursor.getColumnIndexOrThrow(StoriesPersistenceContract.StoryEntry.COLUMN_NAME_TITLE)); Story story = new Story(storyId, title); storyList.add(story); } } if (cursor != null) { cursor.close(); } database.close(); if (storyList.size() == 0) { return Observable.empty(); } else { return Observable.just(storyList); } } @Override
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataSource.java // public interface StoriesDataSource { // // Observable<List<Story>> getStories(String date); // // Observable<StoryDetail> getStoryDetail(int storyId); // // void saveStories(@NonNull List<Story> storyList); // // void refreshStories(); // // void deleteAllStories(); // // } // Path: app/src/main/java/org/attentiveness/news/data/source/local/LocalStoriesDataSource.java import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.data.source.StoriesDataSource; import java.util.ArrayList; import java.util.List; import io.reactivex.Observable; } @Override public Observable<List<Story>> getStories(String date) { List<Story> storyList = new ArrayList<>(); SQLiteDatabase database = this.mDbHelper.getReadableDatabase(); String[] projections = { StoriesPersistenceContract.StoryEntry.COLUMN_NAME_STORY_ID, StoriesPersistenceContract.StoryEntry.COLUMN_NAME_TITLE}; Cursor cursor = database.query(StoriesPersistenceContract.StoryEntry.TABLE_NAME, projections, null, null, null, null, null); if (cursor != null && cursor.getCount() > 0) { while (cursor.moveToNext()) { int storyId = cursor.getInt(cursor.getColumnIndexOrThrow(StoriesPersistenceContract.StoryEntry.COLUMN_NAME_STORY_ID)); String title = cursor.getString(cursor.getColumnIndexOrThrow(StoriesPersistenceContract.StoryEntry.COLUMN_NAME_TITLE)); Story story = new Story(storyId, title); storyList.add(story); } } if (cursor != null) { cursor.close(); } database.close(); if (storyList.size() == 0) { return Observable.empty(); } else { return Observable.just(storyList); } } @Override
public Observable<StoryDetail> getStoryDetail(int storyId) {
attentiveness/News
app/src/main/java/org/attentiveness/news/net/StoryService.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import org.attentiveness.news.data.News; import org.attentiveness.news.data.StoryDetail; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path;
package org.attentiveness.news.net; public interface StoryService { @GET("before/{date}")
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/net/StoryService.java import org.attentiveness.news.data.News; import org.attentiveness.news.data.StoryDetail; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; package org.attentiveness.news.net; public interface StoryService { @GET("before/{date}")
Observable<News> getStoryList(@Path("date") String date);
attentiveness/News
app/src/main/java/org/attentiveness/news/net/StoryService.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import org.attentiveness.news.data.News; import org.attentiveness.news.data.StoryDetail; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path;
package org.attentiveness.news.net; public interface StoryService { @GET("before/{date}") Observable<News> getStoryList(@Path("date") String date); @GET("{id}")
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/net/StoryService.java import org.attentiveness.news.data.News; import org.attentiveness.news.data.StoryDetail; import io.reactivex.Observable; import retrofit2.http.GET; import retrofit2.http.Path; package org.attentiveness.news.net; public interface StoryService { @GET("before/{date}") Observable<News> getStoryList(@Path("date") String date); @GET("{id}")
Observable<StoryDetail> getStoryDetail(@Path("id") int storyId);
attentiveness/News
app/src/main/java/org/attentiveness/news/data/source/StoriesDataRepository.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate;
package org.attentiveness.news.data.source; public class StoriesDataRepository implements StoriesDataSource { private static StoriesDataRepository INSTANCE = null; private final StoriesDataSource mStoriesRemoteDataSource; private final StoriesDataSource mStoriesLocalDataSource; /** * This variable has package local visibility so it can be accessed from tests. */
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataRepository.java import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; package org.attentiveness.news.data.source; public class StoriesDataRepository implements StoriesDataSource { private static StoriesDataRepository INSTANCE = null; private final StoriesDataSource mStoriesRemoteDataSource; private final StoriesDataSource mStoriesLocalDataSource; /** * This variable has package local visibility so it can be accessed from tests. */
private Map<Integer, Story> mCachedStories;
attentiveness/News
app/src/main/java/org/attentiveness/news/data/source/StoriesDataRepository.java
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // }
import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate;
public Observable<List<Story>> getStories(String date) { if (this.mCachedStories != null && !this.mCacheIsDirty) { List<Story> storyList = (List<Story>) this.mCachedStories.values(); return Observable.just(storyList); } Observable<List<Story>> remoteStoryList = this.getAndSaveStoryListFromRemote(date); if (this.mCacheIsDirty) { return remoteStoryList; } else { Observable<List<Story>> localStoryList = this.getAndSaveStoryListFromLocal(date); return Observable.concat(localStoryList, remoteStoryList) .filter(new Predicate<List<Story>>() { @Override public boolean test(@io.reactivex.annotations.NonNull List<Story> storyList) throws Exception { return storyList != null && storyList.size() > 0; } }) .firstElement() .toObservable(); } } /** * Get story detail. Now it just gets data from remote source, not from local source and not * cache the story detail. * * @param storyId Each story has one unique id. * @return Observable wraps story detail. */ @Override
// Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // Path: app/src/main/java/org/attentiveness/news/data/source/StoriesDataRepository.java import android.support.annotation.NonNull; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import java.util.HashMap; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; public Observable<List<Story>> getStories(String date) { if (this.mCachedStories != null && !this.mCacheIsDirty) { List<Story> storyList = (List<Story>) this.mCachedStories.values(); return Observable.just(storyList); } Observable<List<Story>> remoteStoryList = this.getAndSaveStoryListFromRemote(date); if (this.mCacheIsDirty) { return remoteStoryList; } else { Observable<List<Story>> localStoryList = this.getAndSaveStoryListFromLocal(date); return Observable.concat(localStoryList, remoteStoryList) .filter(new Predicate<List<Story>>() { @Override public boolean test(@io.reactivex.annotations.NonNull List<Story> storyList) throws Exception { return storyList != null && storyList.size() > 0; } }) .firstElement() .toObservable(); } } /** * Get story detail. Now it just gets data from remote source, not from local source and not * cache the story detail. * * @param storyId Each story has one unique id. * @return Observable wraps story detail. */ @Override
public Observable<StoryDetail> getStoryDetail(int storyId) {
attentiveness/News
app/src/main/java/org/attentiveness/news/net/HttpManager.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package org.attentiveness.news.net; /** * Http Manager that responds to url request. */ public class HttpManager { private static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/"; private static HttpManager INSTANCE = null; private Context mContext; private StoryService mStoryService; public static HttpManager getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); }
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // } // Path: app/src/main/java/org/attentiveness/news/net/HttpManager.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package org.attentiveness.news.net; /** * Http Manager that responds to url request. */ public class HttpManager { private static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/"; private static HttpManager INSTANCE = null; private Context mContext; private StoryService mStoryService; public static HttpManager getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); }
public Observable<List<Story>> getStoryList(String date) {
attentiveness/News
app/src/main/java/org/attentiveness/news/net/HttpManager.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
package org.attentiveness.news.net; /** * Http Manager that responds to url request. */ public class HttpManager { private static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/"; private static HttpManager INSTANCE = null; private Context mContext; private StoryService mStoryService; public static HttpManager getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() {
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // } // Path: app/src/main/java/org/attentiveness/news/net/HttpManager.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; package org.attentiveness.news.net; /** * Http Manager that responds to url request. */ public class HttpManager { private static final String BASE_URL = "http://news-at.zhihu.com/api/4/news/"; private static HttpManager INSTANCE = null; private Context mContext; private StoryService mStoryService; public static HttpManager getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() {
return new NetworkException(mContext.getResources().getString(R.string.error_no_network_connection));
attentiveness/News
app/src/main/java/org/attentiveness/news/net/HttpManager.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() { return new NetworkException(mContext.getResources().getString(R.string.error_no_network_connection)); } }); }
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // } // Path: app/src/main/java/org/attentiveness/news/net/HttpManager.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; if (INSTANCE == null) { INSTANCE = new HttpManager(context); } return INSTANCE; } /** * Both connection time and read time are 10,000ms by default. */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() { return new NetworkException(mContext.getResources().getString(R.string.error_no_network_connection)); } }); }
return this.mStoryService.getStoryList(date).map(new Function<News, List<Story>>() {
attentiveness/News
app/src/main/java/org/attentiveness/news/net/HttpManager.java
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // }
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory;
*/ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() { return new NetworkException(mContext.getResources().getString(R.string.error_no_network_connection)); } }); } return this.mStoryService.getStoryList(date).map(new Function<News, List<Story>>() { @Override public List<Story> apply(@NonNull News news) throws Exception { return news.getStoryList(); } }); }
// Path: app/src/main/java/org/attentiveness/news/data/News.java // public class News { // // @SerializedName("date") // private String date; // // @SerializedName("stories") // private List<Story> storyList; // // @SerializedName("top_stories") // private List<Story> topStoryList; // // public News() { // // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public List<Story> getStoryList() { // return storyList; // } // // public void setStoryList(List<Story> storyList) { // this.storyList = storyList; // } // // public List<Story> getTopStoryList() { // return topStoryList; // } // // public void setTopStoryList(List<Story> topStoryList) { // this.topStoryList = topStoryList; // } // // } // // Path: app/src/main/java/org/attentiveness/news/data/Story.java // public class Story { // // private int id; // private String title; // // @SerializedName("images") // private List<String> imageList; // // public Story() { // // } // // public Story(int id, String title) { // this.id = id; // this.title = title; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public List<String> getImageList() { // return imageList; // } // // public void setImageList(List<String> imageList) { // this.imageList = imageList; // } // } // // Path: app/src/main/java/org/attentiveness/news/data/StoryDetail.java // public class StoryDetail { // // @SerializedName("id") // private int id; // // @SerializedName("body") // private String content; // // @SerializedName("title") // private String title; // // @SerializedName("image") // private String imageUrl; // // @SerializedName("image_source") // private String imageSource; // // @SerializedName("js") // private List<String> jsList; // // @SerializedName("css") // private List<String> cssList; // // public StoryDetail() { // // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // public String getImageSource() { // return imageSource; // } // // public void setImageSource(String imageSource) { // this.imageSource = imageSource; // } // // public List<String> getJsList() { // return jsList; // } // // public void setJsList(List<String> jsList) { // this.jsList = jsList; // } // // public List<String> getCssList() { // return cssList; // } // // public void setCssList(List<String> cssList) { // this.cssList = cssList; // } // } // // Path: app/src/main/java/org/attentiveness/news/exception/NetworkException.java // public class NetworkException extends Exception { // // public NetworkException() { // super(); // } // // public NetworkException(Throwable throwable) { // super(throwable); // } // // public NetworkException(String message) { // super(message); // } // } // Path: app/src/main/java/org/attentiveness/news/net/HttpManager.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import org.attentiveness.news.R; import org.attentiveness.news.data.News; import org.attentiveness.news.data.Story; import org.attentiveness.news.data.StoryDetail; import org.attentiveness.news.exception.NetworkException; import java.util.List; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; */ private HttpManager(Context context) { this.mContext = context; OkHttpClient client = new OkHttpClient.Builder().build(); Retrofit retrofit = new Retrofit.Builder() .client(client) .baseUrl(BASE_URL) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build(); this.mStoryService = retrofit.create(StoryService.class); } public Observable<List<Story>> getStoryList(String date) { if (!this.isConnected()) { return Observable.error(new Callable<Throwable>() { @Override public Throwable call() { return new NetworkException(mContext.getResources().getString(R.string.error_no_network_connection)); } }); } return this.mStoryService.getStoryList(date).map(new Function<News, List<Story>>() { @Override public List<Story> apply(@NonNull News news) throws Exception { return news.getStoryList(); } }); }
public Observable<StoryDetail> getStory(int storyId) {
transducens/forecat
src/org/forecat/shared/ranker/RankerComposite.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput;
package org.forecat.shared.ranker; /** * Composes a pair of rankers so one is applied before the other. * * @author Daniel Torregrosa * */ public class RankerComposite extends RankerShared { private static final long serialVersionUID = -1229745996571442964L; RankerShared applyBefore = null; RankerShared applyAfter = null; protected RankerComposite() { } public RankerComposite(RankerShared before, RankerShared after) { applyBefore = before; applyAfter = after; } @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerComposite.java import java.util.ArrayList; import java.util.List; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; package org.forecat.shared.ranker; /** * Composes a pair of rankers so one is applied before the other. * * @author Daniel Torregrosa * */ public class RankerComposite extends RankerShared { private static final long serialVersionUID = -1229745996571442964L; RankerShared applyBefore = null; RankerShared applyAfter = null; protected RankerComposite() { } public RankerComposite(RankerShared before, RankerShared after) { applyBefore = before; applyAfter = after; } @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankInp,
transducens/forecat
src/org/forecat/shared/ranker/RankerPosition.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort;
package org.forecat.shared.ranker; /** * Chooses the closest suggestions * * @author Daniel Torregrosa * */ public class RankerPosition extends RankerShared { private static final long serialVersionUID = 185266502718735714L; @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerPosition.java import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; package org.forecat.shared.ranker; /** * Chooses the closest suggestions * * @author Daniel Torregrosa * */ public class RankerPosition extends RankerShared { private static final long serialVersionUID = 185266502718735714L; @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankInp,
transducens/forecat
src/org/forecat/server/translation/cachetrans/Cachetrans.java
// Path: src/org/forecat/console/utils/UtilsConsole.java // public class UtilsConsole { // public static InputStream openFile(String file) { // InputStream ret = null; // // ret = Main.class.getResourceAsStream(file); // // if (ret == null) { // try { // ret = new FileInputStream(file); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return ret; // } // // public static Integer multiMax(Integer a, Integer... b) { // for (Integer i : b) { // a = Math.max(a, i); // } // // return a; // } // }
import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.collections4.map.MultiValueMap; import org.forecat.console.utils.UtilsConsole; import org.forecat.shared.translation.SourceSegment;
continue; } sourceWord = sourceSplit[i]; targetWord = targetSplit[i]; if (Character.isUpperCase(sourceWord.charAt(0))) { if (sourceWord.length() > 1 && Character.isUpperCase(sourceWord.charAt(1)) || targetWord.length() == 0) { sb.append(targetWord.toUpperCase()); } else { sb.append(Character.toUpperCase(targetWord.charAt(0))); sb.append(targetWord.substring(1)); } } else { sb.append(targetWord); } } return sb.toString(); } public static void loadSegments(String slang, String tlang) throws IOException { InputStream sSource = null, tSource = null; String sSeg, tSeg; BufferedReader sBr, tBr; String lang = slang + "-" + tlang; // String ordLang = slang.compareTo(tlang) < 0 ? slang + "-" + tlang : tlang + "-" + slang; HashMap<String, String> auxSegments = new HashMap<String, String>(); if (!segments.containsKey(lang)) {
// Path: src/org/forecat/console/utils/UtilsConsole.java // public class UtilsConsole { // public static InputStream openFile(String file) { // InputStream ret = null; // // ret = Main.class.getResourceAsStream(file); // // if (ret == null) { // try { // ret = new FileInputStream(file); // } catch (FileNotFoundException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // return ret; // } // // public static Integer multiMax(Integer a, Integer... b) { // for (Integer i : b) { // a = Math.max(a, i); // } // // return a; // } // } // Path: src/org/forecat/server/translation/cachetrans/Cachetrans.java import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.apache.commons.collections4.map.MultiValueMap; import org.forecat.console.utils.UtilsConsole; import org.forecat.shared.translation.SourceSegment; continue; } sourceWord = sourceSplit[i]; targetWord = targetSplit[i]; if (Character.isUpperCase(sourceWord.charAt(0))) { if (sourceWord.length() > 1 && Character.isUpperCase(sourceWord.charAt(1)) || targetWord.length() == 0) { sb.append(targetWord.toUpperCase()); } else { sb.append(Character.toUpperCase(targetWord.charAt(0))); sb.append(targetWord.substring(1)); } } else { sb.append(targetWord); } } return sb.toString(); } public static void loadSegments(String slang, String tlang) throws IOException { InputStream sSource = null, tSource = null; String sSeg, tSeg; BufferedReader sBr, tBr; String lang = slang + "-" + tlang; // String ordLang = slang.compareTo(tlang) < 0 ? slang + "-" + tlang : tlang + "-" + slang; HashMap<String, String> auxSegments = new HashMap<String, String>(); if (!segments.containsKey(lang)) {
InputStream config = UtilsConsole.openFile(configFile);
transducens/forecat
src/org/forecat/shared/suggestions/SuggestionsBasic.java
// Path: src/org/forecat/shared/utils/SubIdProvider.java // public class SubIdProvider { // // public static class Pair { // private final String l; // private final SourceSegment r; // // public Pair(String l, SourceSegment r) { // this.l = l; // this.r = r; // } // } // // static ArrayList<Pair> subids = new ArrayList<Pair>(); // public static boolean isWorking = false; // // public static void addElement(String s, SourceSegment ss) { // if (isWorking) // subids.add(new Pair(s, ss)); // } // // public static int getSubId(String s, SourceSegment ss) { // if (isWorking) { // return subids.indexOf(new Pair(s, ss)); // } // return 0; // } // // public static void clear() { // subids.clear(); // } // }
import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import org.forecat.shared.translation.SourceSegment; import org.forecat.shared.utils.SubIdProvider; import org.forecat.shared.utils.UtilsShared; import com.google.gwt.user.client.rpc.IsSerializable;
package org.forecat.shared.suggestions; public class SuggestionsBasic extends SuggestionsShared implements IsSerializable, Serializable { /** * */ private static final long serialVersionUID = 1267521779646327709L; @Override public List<SuggestionsOutput> obtainSuggestions(SuggestionsInput input, Map<String, List<SourceSegment>> segmentPairs, Map<String, Integer> segmentCounts) { // SuggestionsOutput includes a compareTo method. SortedSet<SuggestionsOutput> preoutput = new TreeSet<SuggestionsOutput>(); int closerPositionWords, closerDifference, closerPositionChars, i; Iterator<Entry<String, List<SourceSegment>>> it = segmentPairs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, List<SourceSegment>> e = it.next(); // Search for the closest source segment that could have generated this suggestion closerPositionWords = -1; closerDifference = 0; closerPositionChars = 0; String originText = ""; String closerId = ""; for (SourceSegment ss : segmentPairs.get(e.getKey())) { if (closerPositionWords == -1) { closerPositionWords = ss.getPosition(); closerDifference = Math.abs(ss.getPosition() - input.getPosition());
// Path: src/org/forecat/shared/utils/SubIdProvider.java // public class SubIdProvider { // // public static class Pair { // private final String l; // private final SourceSegment r; // // public Pair(String l, SourceSegment r) { // this.l = l; // this.r = r; // } // } // // static ArrayList<Pair> subids = new ArrayList<Pair>(); // public static boolean isWorking = false; // // public static void addElement(String s, SourceSegment ss) { // if (isWorking) // subids.add(new Pair(s, ss)); // } // // public static int getSubId(String s, SourceSegment ss) { // if (isWorking) { // return subids.indexOf(new Pair(s, ss)); // } // return 0; // } // // public static void clear() { // subids.clear(); // } // } // Path: src/org/forecat/shared/suggestions/SuggestionsBasic.java import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; import org.forecat.shared.translation.SourceSegment; import org.forecat.shared.utils.SubIdProvider; import org.forecat.shared.utils.UtilsShared; import com.google.gwt.user.client.rpc.IsSerializable; package org.forecat.shared.suggestions; public class SuggestionsBasic extends SuggestionsShared implements IsSerializable, Serializable { /** * */ private static final long serialVersionUID = 1267521779646327709L; @Override public List<SuggestionsOutput> obtainSuggestions(SuggestionsInput input, Map<String, List<SourceSegment>> segmentPairs, Map<String, Integer> segmentCounts) { // SuggestionsOutput includes a compareTo method. SortedSet<SuggestionsOutput> preoutput = new TreeSet<SuggestionsOutput>(); int closerPositionWords, closerDifference, closerPositionChars, i; Iterator<Entry<String, List<SourceSegment>>> it = segmentPairs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, List<SourceSegment>> e = it.next(); // Search for the closest source segment that could have generated this suggestion closerPositionWords = -1; closerDifference = 0; closerPositionChars = 0; String originText = ""; String closerId = ""; for (SourceSegment ss : segmentPairs.get(e.getKey())) { if (closerPositionWords == -1) { closerPositionWords = ss.getPosition(); closerDifference = Math.abs(ss.getPosition() - input.getPosition());
closerId = ss.getId() + "." + SubIdProvider.getSubId(e.getKey(), ss);
transducens/forecat
src/org/forecat/shared/suggestions/SuggestionsShared.java
// Path: src/org/forecat/shared/SessionShared.java // public interface SessionShared { // public void setAttribute(String key, Object value); // // public Object getAttribute(String key); // // public String getId(); // }
import java.util.List; import java.util.Map; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.SessionShared; import org.forecat.shared.translation.SourceSegment;
package org.forecat.shared.suggestions; public abstract class SuggestionsShared { protected int frame = 0; public abstract List<SuggestionsOutput> obtainSuggestions(SuggestionsInput input, Map<String, List<SourceSegment>> segmentPairs, Map<String, Integer> segmentCounts); public SuggestionsShared() { super(); } public void setFrame(int f) { frame = f; }
// Path: src/org/forecat/shared/SessionShared.java // public interface SessionShared { // public void setAttribute(String key, Object value); // // public Object getAttribute(String key); // // public String getId(); // } // Path: src/org/forecat/shared/suggestions/SuggestionsShared.java import java.util.List; import java.util.Map; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.SessionShared; import org.forecat.shared.translation.SourceSegment; package org.forecat.shared.suggestions; public abstract class SuggestionsShared { protected int frame = 0; public abstract List<SuggestionsOutput> obtainSuggestions(SuggestionsInput input, Map<String, List<SourceSegment>> segmentPairs, Map<String, Integer> segmentCounts); public SuggestionsShared() { super(); } public void setFrame(int f) { frame = f; }
public List<SuggestionsOutput> suggestionsService(SuggestionsInput input, SessionShared session) throws ForecatException {
transducens/forecat
src/org/forecat/shared/translation/TranslationInput.java
// Path: src/org/forecat/client/translation/TranslationInputJso.java // public class TranslationInputJso extends JavaScriptObject { // // protected TranslationInputJso() { // } // // public final native String getSourceText() /*-{ // return this.sourceText; // }-*/; // // public final native String getSourceCode() /*-{ // return this.sourceCode; // }-*/; // // public final native String getTargetCode() /*-{ // return this.targetCode; // }-*/; // // public final native int getMaxSegmentLength() /*-{ // return this.maxSegmentLength; // }-*/; // // public final native int getMinSegmentLength() /*-{ // return this.minSegmentLength; // }-*/; // // }
import java.io.Serializable; import org.forecat.client.translation.TranslationInputJso; import com.google.gwt.user.client.rpc.IsSerializable;
package org.forecat.shared.translation; @SuppressWarnings("serial") public class TranslationInput implements Serializable, IsSerializable { String sourceText; String sourceCode; String targetCode; int maxSegmentLength; int minSegmentLength; /** * From Serializable documentation * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes * of non-serializable classes to be serialized, the subtype may assume responsibility for * saving and restoring the state of the supertype's public, protected, and (if accessible) * package fields. The subtype may assume this responsibility only if the class it extends has * an accessible no-arg constructor to initialize the class's state. It is an error to declare a * class Serializable if this is not the case. The error will be detected at runtime." */ protected TranslationInput() { } public TranslationInput(String sourceText, String sourceCode, String targetCode, int maxSegmentLength, int minSegmentLength) { this.sourceText = sourceText; this.sourceCode = sourceCode; this.targetCode = targetCode; this.maxSegmentLength = maxSegmentLength; this.minSegmentLength = minSegmentLength; }
// Path: src/org/forecat/client/translation/TranslationInputJso.java // public class TranslationInputJso extends JavaScriptObject { // // protected TranslationInputJso() { // } // // public final native String getSourceText() /*-{ // return this.sourceText; // }-*/; // // public final native String getSourceCode() /*-{ // return this.sourceCode; // }-*/; // // public final native String getTargetCode() /*-{ // return this.targetCode; // }-*/; // // public final native int getMaxSegmentLength() /*-{ // return this.maxSegmentLength; // }-*/; // // public final native int getMinSegmentLength() /*-{ // return this.minSegmentLength; // }-*/; // // } // Path: src/org/forecat/shared/translation/TranslationInput.java import java.io.Serializable; import org.forecat.client.translation.TranslationInputJso; import com.google.gwt.user.client.rpc.IsSerializable; package org.forecat.shared.translation; @SuppressWarnings("serial") public class TranslationInput implements Serializable, IsSerializable { String sourceText; String sourceCode; String targetCode; int maxSegmentLength; int minSegmentLength; /** * From Serializable documentation * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes * of non-serializable classes to be serialized, the subtype may assume responsibility for * saving and restoring the state of the supertype's public, protected, and (if accessible) * package fields. The subtype may assume this responsibility only if the class it extends has * an accessible no-arg constructor to initialize the class's state. It is an error to declare a * class Serializable if this is not the case. The error will be detected at runtime." */ protected TranslationInput() { } public TranslationInput(String sourceText, String sourceCode, String targetCode, int maxSegmentLength, int minSegmentLength) { this.sourceText = sourceText; this.sourceCode = sourceCode; this.targetCode = targetCode; this.maxSegmentLength = maxSegmentLength; this.minSegmentLength = minSegmentLength; }
public TranslationInput(TranslationInputJso jso) {
transducens/forecat
src/org/forecat/shared/ranker/RankerShortestLongestFirst.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort;
package org.forecat.shared.ranker; /** * Alternates the shortest and longest suggestions * * @author Daniel Torregrosa * */ public class RankerShortestLongestFirst extends RankerShared { private static final long serialVersionUID = -5509552226829972825L; @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerShortestLongestFirst.java import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; package org.forecat.shared.ranker; /** * Alternates the shortest and longest suggestions * * @author Daniel Torregrosa * */ public class RankerShortestLongestFirst extends RankerShared { private static final long serialVersionUID = -5509552226829972825L; @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankInp,
transducens/forecat
src/org/forecat/shared/selection/SelectionInput.java
// Path: src/org/forecat/client/selection/SelectionInputJso.java // public class SelectionInputJso extends JavaScriptObject { // // protected SelectionInputJso() { // } // // public final native String getSelectionText() /*-{ // return this.selectionText; // }-*/; // // public final native int getPosition() /*-{ // return this.position; // }-*/; // // public final native String getId() /*-{ // return this.id; // }-*/; // // }
import java.io.Serializable; import org.forecat.client.selection.SelectionInputJso; import com.google.gwt.user.client.rpc.IsSerializable;
package org.forecat.shared.selection; @SuppressWarnings("serial") public class SelectionInput implements Serializable, IsSerializable { private String selectionText; private int position; private String id; /** * From Serializable documentation * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes * of non-serializable classes to be serialized, the subtype may assume responsibility for * saving and restoring the state of the supertype's public, protected, and (if accessible) * package fields. The subtype may assume this responsibility only if the class it extends has * an accessible no-arg constructor to initialize the class's state. It is an error to declare a * class Serializable if this is not the case. The error will be detected at runtime." */ protected SelectionInput() { } public SelectionInput(String selectionText, int position) { this.selectionText = selectionText; this.position = position; }
// Path: src/org/forecat/client/selection/SelectionInputJso.java // public class SelectionInputJso extends JavaScriptObject { // // protected SelectionInputJso() { // } // // public final native String getSelectionText() /*-{ // return this.selectionText; // }-*/; // // public final native int getPosition() /*-{ // return this.position; // }-*/; // // public final native String getId() /*-{ // return this.id; // }-*/; // // } // Path: src/org/forecat/shared/selection/SelectionInput.java import java.io.Serializable; import org.forecat.client.selection.SelectionInputJso; import com.google.gwt.user.client.rpc.IsSerializable; package org.forecat.shared.selection; @SuppressWarnings("serial") public class SelectionInput implements Serializable, IsSerializable { private String selectionText; private int position; private String id; /** * From Serializable documentation * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes * of non-serializable classes to be serialized, the subtype may assume responsibility for * saving and restoring the state of the supertype's public, protected, and (if accessible) * package fields. The subtype may assume this responsibility only if the class it extends has * an accessible no-arg constructor to initialize the class's state. It is an error to declare a * class Serializable if this is not the case. The error will be detected at runtime." */ protected SelectionInput() { } public SelectionInput(String selectionText, int position) { this.selectionText = selectionText; this.position = position; }
public SelectionInput(SelectionInputJso jso) {
transducens/forecat
src/org/forecat/shared/ranker/RankerShortestFirst.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort;
package org.forecat.shared.ranker; /** * Chooses the shortest suggestions. * * @author Daniel Torregrosa * */ public class RankerShortestFirst extends RankerShared { private static final long serialVersionUID = -8938351457344546500L; @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerShortestFirst.java import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; package org.forecat.shared.ranker; /** * Chooses the shortest suggestions. * * @author Daniel Torregrosa * */ public class RankerShortestFirst extends RankerShared { private static final long serialVersionUID = -8938351457344546500L; @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankInp,
transducens/forecat
src/org/forecat/shared/ranker/RankerNeuralNetwork.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; import com.googlecode.fannj.Fann;
* 67@attribute distribution_diff_C=M numeric * * 68@attribute distribution_ratio_C=H numeric * * 69@attribute distribution_ratio_C=D numeric * * 70@attribute distribution_ratio_C=DD numeric * * 71@attribute distribution_ratio_C=M numeric * * 72@attribute distribution_diffN numeric * * 73@attribute distribution_ratioN numeric * * 74@attribute fromUsed=FROM_TYPING numeric * * 75@attribute overlapping=B numeric * * 76@attribute overlapping=JB numeric * * 77@attribute overlapping=O numeric * * 78@attribute overlapping=JA numeric * * 79@attribute overlapping=A numeric * * */ @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerNeuralNetwork.java import java.util.ArrayList; import java.util.List; import org.apache.commons.math3.util.Pair; import org.forecat.client.exceptions.ForecatException; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; import com.googlecode.fannj.Fann; * 67@attribute distribution_diff_C=M numeric * * 68@attribute distribution_ratio_C=H numeric * * 69@attribute distribution_ratio_C=D numeric * * 70@attribute distribution_ratio_C=DD numeric * * 71@attribute distribution_ratio_C=M numeric * * 72@attribute distribution_diffN numeric * * 73@attribute distribution_ratioN numeric * * 74@attribute fromUsed=FROM_TYPING numeric * * 75@attribute overlapping=B numeric * * 76@attribute overlapping=JB numeric * * 77@attribute overlapping=O numeric * * 78@attribute overlapping=JA numeric * * 79@attribute overlapping=A numeric * * */ @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankinp,
transducens/forecat
src/org/forecat/shared/ranker/RankerLongestFirst.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort;
package org.forecat.shared.ranker; /** * Chooses the longest suggestions * * @author Daniel Torregrosa * */ public class RankerLongestFirst extends RankerShared { private static final long serialVersionUID = 896290267380126773L; @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerLongestFirst.java import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; package org.forecat.shared.ranker; /** * Chooses the longest suggestions * * @author Daniel Torregrosa * */ public class RankerLongestFirst extends RankerShared { private static final long serialVersionUID = 896290267380126773L; @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankinput,
transducens/forecat
src/org/forecat/shared/ranker/RankerLongestShortestFirst.java
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // }
import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort;
package org.forecat.shared.ranker; /** * Alternates between the longest and shortest suggestions * * @author Daniel Torregrosa * */ public class RankerLongestShortestFirst extends RankerShared { private static final long serialVersionUID = 2151574862257494336L; @Override
// Path: src/org/forecat/shared/suggestions/SuggestionsOutput.java // @SuppressWarnings("serial") // public class SuggestionsOutput // implements Serializable, Comparable<SuggestionsOutput>, IsSerializable { // // String suggestionText; // double suggestionFeasibility; // String originalText; // // /** // * Position of origin of the suggestion (in source language) // */ // int wordPosition; // int charPosition; // // /** // * Number of words of the origin suggestion // */ // int numberWords; // // /** // * Id of the SourceSegment // */ // String id; // // /** // * From Serializable documentation // * (http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html): "To allow subtypes // * of non-serializable classes to be serialized, the subtype may assume responsibility for // * saving and restoring the state of the supertype's public, protected, and (if accessible) // * package fields. The subtype may assume this responsibility only if the class it extends has // * an accessible no-arg constructor to initialize the class's state. It is an error to declare a // * class Serializable if this is not the case. The error will be detected at runtime." // */ // protected SuggestionsOutput() { // } // // public SuggestionsOutput(String suggestionText, String origText, double suggestionFeasibility, // String id, int wordPosition, int charPosition) { // this.suggestionText = suggestionText; // this.originalText = origText; // this.suggestionFeasibility = suggestionFeasibility; // this.id = id; // this.wordPosition = wordPosition; // this.charPosition = charPosition; // } // // public void setSuggestionText(String suggestionText) { // this.suggestionText = suggestionText; // } // // public String getSuggestionText() { // return suggestionText; // } // // public void setSuggestionFeasibility(double suggestionFeasibility) { // this.suggestionFeasibility = suggestionFeasibility; // } // // public double getSuggestionFeasibility() { // return suggestionFeasibility; // } // // public String getId() { // return id; // } // // public int getWordPosition() { // return wordPosition; // } // // public int getCharPosition() { // return charPosition; // } // // public int getSuggestionWordLength() { // if ("".equals(suggestionText)) // return 0; // return suggestionText.split(" ").length; // } // // public int getSuggestionCharLength() { // return suggestionText.length(); // } // // public String getOriginal() { // return originalText; // } // // public int getOriginalWordLength() { // if ("".equals(originalText)) // return 0; // return originalText.split(" ").length; // } // // public int getOriginalCharLength() { // return originalText.length(); // } // // /** // * Suggestions with higher feasibilities go first. If equal, promote shortest ones. // * // * @param s // * @return // */ // @Override // public int compareTo(SuggestionsOutput s) { // final int BEFORE = -1; // final int EQUAL = 0; // final int AFTER = 1; // // if (this == s) { // return EQUAL; // } // // int comparison = Double.compare(this.suggestionFeasibility, s.suggestionFeasibility); // if (comparison != EQUAL) { // return -comparison; // } // // if (this.suggestionText.length() < s.suggestionText.length()) { // return BEFORE; // } // if (this.suggestionText.length() > s.suggestionText.length()) { // return AFTER; // } // // return this.suggestionText.compareTo(s.suggestionText); // // // // if (this.suggestionText.equals(s.suggestionText)) // // return EQUAL; // // return BEFORE; // } // } // Path: src/org/forecat/shared/ranker/RankerLongestShortestFirst.java import java.util.ArrayList; import java.util.List; import org.forecat.shared.suggestions.SuggestionsInput; import org.forecat.shared.suggestions.SuggestionsOutput; import org.forecat.shared.utils.Quicksort; package org.forecat.shared.ranker; /** * Alternates between the longest and shortest suggestions * * @author Daniel Torregrosa * */ public class RankerLongestShortestFirst extends RankerShared { private static final long serialVersionUID = 2151574862257494336L; @Override
public List<SuggestionsOutput> rankerService(SuggestionsInput rankInp,
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring;
/* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 12-Mar-2012 */ public class UsesDirectiveResolverTest extends AbstractResolverTest { @Test public void testMultipleProviders() throws Exception { // Bundle-SymbolicName: javax.servlet.api // ExportPackage: javax.servlet;version=2.5 final JavaArchive archiveA = ShrinkWrap.create(JavaArchive.class, "javax.servlet.api"); archiveA.setManifest(new Asset() { @Override public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName(archiveA.getName()); builder.addExportPackages("javax.servlet;version=2.5"); return builder.openStream(); } });
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; /* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 12-Mar-2012 */ public class UsesDirectiveResolverTest extends AbstractResolverTest { @Test public void testMultipleProviders() throws Exception { // Bundle-SymbolicName: javax.servlet.api // ExportPackage: javax.servlet;version=2.5 final JavaArchive archiveA = ShrinkWrap.create(JavaArchive.class, "javax.servlet.api"); archiveA.setManifest(new Asset() { @Override public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName(archiveA.getName()); builder.addExportPackages("javax.servlet;version=2.5"); return builder.openStream(); } });
XResource resourceA = createResource(archiveA);
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring;
Assert.assertEquals(0, wiringA.getResourceRequirements(PACKAGE_NAMESPACE).size()); List<Capability> caps = wiringA.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(1, caps.size()); Assert.assertEquals("javax.servlet", getPackageName(caps.get(0))); // Verify wiring of B Wiring wiringB = getWiring(resourceB); wires = wiringB.getRequiredResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceA, wires.get(0).getProvider()); Assert.assertEquals(0, wiringB.getProvidedResourceWires(null).size()); List<Requirement> reqs = wiringB.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size()); caps = wiringB.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(1, caps.size()); Assert.assertEquals("org.osgi.service.http", getPackageName(caps.get(0))); // Verify wiring of C Wiring wiringC = getWiring(resourceC); wires = wiringC.getRequiredResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceA, wires.get(0).getProvider()); wires = wiringC.getProvidedResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceD, wires.get(0).getRequirer()); reqs = wiringC.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size());
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; Assert.assertEquals(0, wiringA.getResourceRequirements(PACKAGE_NAMESPACE).size()); List<Capability> caps = wiringA.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(1, caps.size()); Assert.assertEquals("javax.servlet", getPackageName(caps.get(0))); // Verify wiring of B Wiring wiringB = getWiring(resourceB); wires = wiringB.getRequiredResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceA, wires.get(0).getProvider()); Assert.assertEquals(0, wiringB.getProvidedResourceWires(null).size()); List<Requirement> reqs = wiringB.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size()); caps = wiringB.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(1, caps.size()); Assert.assertEquals("org.osgi.service.http", getPackageName(caps.get(0))); // Verify wiring of C Wiring wiringC = getWiring(resourceC); wires = wiringC.getRequiredResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceA, wires.get(0).getProvider()); wires = wiringC.getProvidedResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceD, wires.get(0).getRequirer()); reqs = wiringC.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size());
Assert.assertEquals("javax.servlet", getPackageName((XPackageRequirement) reqs.get(0)));
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring;
Assert.assertSame(resourceA, wires.get(0).getProvider()); wires = wiringC.getProvidedResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceD, wires.get(0).getRequirer()); reqs = wiringC.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size()); Assert.assertEquals("javax.servlet", getPackageName((XPackageRequirement) reqs.get(0))); caps = wiringC.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(2, caps.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(caps.get(0))); Assert.assertEquals("org.osgi.service.http", getPackageName(caps.get(1))); // Verify wiring of D Wiring wiringD = getWiring(resourceD); wires = wiringD.getRequiredResourceWires(null); Assert.assertEquals(2, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceC, wires.get(0).getProvider()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(1).getCapability())); Assert.assertSame(resourceA, wires.get(1).getProvider()); Assert.assertEquals(0, wiringD.getProvidedResourceWires(null).size()); reqs = wiringD.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(2, reqs.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName((XPackageRequirement) reqs.get(0))); Assert.assertEquals("javax.servlet", getPackageName((XPackageRequirement) reqs.get(1))); Assert.assertEquals(0, wiringD.getResourceCapabilities(PACKAGE_NAMESPACE).size()); } private String getPackageName(Capability cap) {
// Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/UsesDirectiveResolverTest.java import static org.junit.Assert.assertEquals; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Capability; import org.osgi.resource.Requirement; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; Assert.assertSame(resourceA, wires.get(0).getProvider()); wires = wiringC.getProvidedResourceWires(null); Assert.assertEquals(1, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceD, wires.get(0).getRequirer()); reqs = wiringC.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(1, reqs.size()); Assert.assertEquals("javax.servlet", getPackageName((XPackageRequirement) reqs.get(0))); caps = wiringC.getResourceCapabilities(PACKAGE_NAMESPACE); Assert.assertEquals(2, caps.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(caps.get(0))); Assert.assertEquals("org.osgi.service.http", getPackageName(caps.get(1))); // Verify wiring of D Wiring wiringD = getWiring(resourceD); wires = wiringD.getRequiredResourceWires(null); Assert.assertEquals(2, wires.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName(wires.get(0).getCapability())); Assert.assertSame(resourceC, wires.get(0).getProvider()); Assert.assertEquals("javax.servlet", getPackageName(wires.get(1).getCapability())); Assert.assertSame(resourceA, wires.get(1).getProvider()); Assert.assertEquals(0, wiringD.getProvidedResourceWires(null).size()); reqs = wiringD.getResourceRequirements(PACKAGE_NAMESPACE); Assert.assertEquals(2, reqs.size()); Assert.assertEquals("org.ops4j.pax.web.service", getPackageName((XPackageRequirement) reqs.get(0))); Assert.assertEquals("javax.servlet", getPackageName((XPackageRequirement) reqs.get(1))); Assert.assertEquals(0, wiringD.getResourceCapabilities(PACKAGE_NAMESPACE).size()); } private String getPackageName(Capability cap) {
return ((XPackageCapability)cap).getPackageName();
jbosgi/jbosgi-resolver
felix/src/main/java/org/apache/felix/resolver/ResolutionError.java
// Path: api/src/main/java/org/osgi/service/resolver/ResolutionException.java // public class ResolutionException extends Exception { // // private static final long serialVersionUID = 1L; // // private transient final Collection<Requirement> unresolvedRequirements; // // /** // * Create a {@code ResolutionException} with the specified message, cause // * and unresolved requirements. // * // * @param message The message. // * @param cause The cause of this exception. // * @param unresolvedRequirements The unresolved mandatory requirements from // * mandatory resources or {@code null} if no unresolved requirements // * information is provided. // */ // public ResolutionException(String message, Throwable cause, Collection<Requirement> unresolvedRequirements) { // super(message, cause); // if ((unresolvedRequirements == null) || unresolvedRequirements.isEmpty()) { // this.unresolvedRequirements = emptyCollection(); // } else { // this.unresolvedRequirements = Collections.unmodifiableCollection(new ArrayList<Requirement>(unresolvedRequirements)); // } // } // // /** // * Create a {@code ResolutionException} with the specified message. // * // * @param message The message. // */ // public ResolutionException(String message) { // super(message); // unresolvedRequirements = emptyCollection(); // } // // /** // * Create a {@code ResolutionException} with the specified cause. // * // * @param cause The cause of this exception. // */ // public ResolutionException(Throwable cause) { // super(cause); // unresolvedRequirements = emptyCollection(); // } // // @SuppressWarnings("unchecked") // private static <T> Collection<T> emptyCollection() { // return Collections.EMPTY_LIST; // } // // /** // * Return the unresolved requirements, if any, for this exception. // * // * <p> // * The unresolved requirements are provided for informational purposes and // * the specific set of unresolved requirements that are provided after a // * resolve failure is not defined. // * // * @return A collection of the unresolved requirements for this exception. // * The returned collection may be empty if no unresolved // * requirements information is provided. // */ // public Collection<Requirement> getUnresolvedRequirements() { // return unresolvedRequirements; // } // }
import java.util.Collections; import org.osgi.resource.Requirement; import org.osgi.service.resolver.ResolutionException; import java.util.Collection;
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.felix.resolver; /** * Resolution error. * This class contains all the needed information to build the ResolutionException * without the need to actually compute a user friendly message, which can be * quite time consuming. */ public abstract class ResolutionError { public abstract String getMessage(); public Collection<Requirement> getUnresolvedRequirements() { return Collections.emptyList(); }
// Path: api/src/main/java/org/osgi/service/resolver/ResolutionException.java // public class ResolutionException extends Exception { // // private static final long serialVersionUID = 1L; // // private transient final Collection<Requirement> unresolvedRequirements; // // /** // * Create a {@code ResolutionException} with the specified message, cause // * and unresolved requirements. // * // * @param message The message. // * @param cause The cause of this exception. // * @param unresolvedRequirements The unresolved mandatory requirements from // * mandatory resources or {@code null} if no unresolved requirements // * information is provided. // */ // public ResolutionException(String message, Throwable cause, Collection<Requirement> unresolvedRequirements) { // super(message, cause); // if ((unresolvedRequirements == null) || unresolvedRequirements.isEmpty()) { // this.unresolvedRequirements = emptyCollection(); // } else { // this.unresolvedRequirements = Collections.unmodifiableCollection(new ArrayList<Requirement>(unresolvedRequirements)); // } // } // // /** // * Create a {@code ResolutionException} with the specified message. // * // * @param message The message. // */ // public ResolutionException(String message) { // super(message); // unresolvedRequirements = emptyCollection(); // } // // /** // * Create a {@code ResolutionException} with the specified cause. // * // * @param cause The cause of this exception. // */ // public ResolutionException(Throwable cause) { // super(cause); // unresolvedRequirements = emptyCollection(); // } // // @SuppressWarnings("unchecked") // private static <T> Collection<T> emptyCollection() { // return Collections.EMPTY_LIST; // } // // /** // * Return the unresolved requirements, if any, for this exception. // * // * <p> // * The unresolved requirements are provided for informational purposes and // * the specific set of unresolved requirements that are provided after a // * resolve failure is not defined. // * // * @return A collection of the unresolved requirements for this exception. // * The returned collection may be empty if no unresolved // * requirements information is provided. // */ // public Collection<Requirement> getUnresolvedRequirements() { // return unresolvedRequirements; // } // } // Path: felix/src/main/java/org/apache/felix/resolver/ResolutionError.java import java.util.Collections; import org.osgi.resource.Requirement; import org.osgi.service.resolver.ResolutionException; import java.util.Collection; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 org.apache.felix.resolver; /** * Resolution error. * This class contains all the needed information to build the ResolutionException * without the need to actually compute a user friendly message, which can be * quite time consuming. */ public abstract class ResolutionError { public abstract String getMessage(); public Collection<Requirement> getUnresolvedRequirements() { return Collections.emptyList(); }
public ResolutionException toException() {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/FrameworkPreferencesComparator.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XEnvironment.java // public interface XEnvironment { // // void installResources(XResource... resources); // // void uninstallResources(XResource... resources); // // XResource getResourceById(long identifier); // // Iterator<XResource> getResources(Collection<String> types); // // Long nextResourceIdentifier(Long value, String symbolicName); // // List<Capability> findProviders(Requirement req); // // Map<Resource, Wiring> updateWiring(Map<Resource, List<Wire>> delta); // // Map<Resource, Wiring> getWirings(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.osgi.resource.Capability; import org.osgi.resource.Resource; import org.osgi.resource.Wiring; import static org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.util.Map; import org.jboss.osgi.resolver.XEnvironment; import org.jboss.osgi.resolver.XResource; import org.osgi.framework.Version; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace;
/* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * A comparator based on defined framework preferences. * * @author thomas.diesler@jboss.com * @since 02-Jul-2010 */ class FrameworkPreferencesComparator extends ResourceIndexComparator { public FrameworkPreferencesComparator(XEnvironment environment) { super(environment); } @Override public int compare(Capability o1, Capability o2) { Resource res1 = o1.getResource(); Resource res2 = o2.getResource(); // prefer system bundle
// Path: api/src/main/java/org/jboss/osgi/resolver/XEnvironment.java // public interface XEnvironment { // // void installResources(XResource... resources); // // void uninstallResources(XResource... resources); // // XResource getResourceById(long identifier); // // Iterator<XResource> getResources(Collection<String> types); // // Long nextResourceIdentifier(Long value, String symbolicName); // // List<Capability> findProviders(Requirement req); // // Map<Resource, Wiring> updateWiring(Map<Resource, List<Wire>> delta); // // Map<Resource, Wiring> getWirings(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/FrameworkPreferencesComparator.java import org.osgi.resource.Capability; import org.osgi.resource.Resource; import org.osgi.resource.Wiring; import static org.osgi.framework.namespace.BundleNamespace.BUNDLE_NAMESPACE; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.util.Map; import org.jboss.osgi.resolver.XEnvironment; import org.jboss.osgi.resolver.XResource; import org.osgi.framework.Version; import org.osgi.framework.namespace.BundleNamespace; import org.osgi.framework.namespace.PackageNamespace; /* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * A comparator based on defined framework preferences. * * @author thomas.diesler@jboss.com * @since 02-Jul-2010 */ class FrameworkPreferencesComparator extends ResourceIndexComparator { public FrameworkPreferencesComparator(XEnvironment environment) { super(environment); } @Override public int compare(Capability o1, Capability o2) { Resource res1 = o1.getResource(); Resource res2 = o2.getResource(); // prefer system bundle
Long in1 = getResourceIndex((XResource) o1.getResource());
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/ResourceIndexComparator.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XEnvironment.java // public interface XEnvironment { // // void installResources(XResource... resources); // // void uninstallResources(XResource... resources); // // XResource getResourceById(long identifier); // // Iterator<XResource> getResources(Collection<String> types); // // Long nextResourceIdentifier(Long value, String symbolicName); // // List<Capability> findProviders(Requirement req); // // Map<Resource, Wiring> updateWiring(Map<Resource, List<Wire>> delta); // // Map<Resource, Wiring> getWirings(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.jboss.osgi.resolver.XEnvironment; import org.jboss.osgi.resolver.XResource; import org.osgi.resource.Capability; import java.util.Comparator;
/* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * A comparator that uses the provided resource index. * * @author thomas.diesler@jboss.com * @since 02-Jul-2010 */ class ResourceIndexComparator implements Comparator<Capability> { private final XEnvironment environment; ResourceIndexComparator(XEnvironment environment) { this.environment = environment; } XEnvironment getEnvironment() { return environment; } @Override public int compare(Capability o1, Capability o2) {
// Path: api/src/main/java/org/jboss/osgi/resolver/XEnvironment.java // public interface XEnvironment { // // void installResources(XResource... resources); // // void uninstallResources(XResource... resources); // // XResource getResourceById(long identifier); // // Iterator<XResource> getResources(Collection<String> types); // // Long nextResourceIdentifier(Long value, String symbolicName); // // List<Capability> findProviders(Requirement req); // // Map<Resource, Wiring> updateWiring(Map<Resource, List<Wire>> delta); // // Map<Resource, Wiring> getWirings(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/ResourceIndexComparator.java import org.jboss.osgi.resolver.XEnvironment; import org.jboss.osgi.resolver.XResource; import org.osgi.resource.Capability; import java.util.Comparator; /* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * A comparator that uses the provided resource index. * * @author thomas.diesler@jboss.com * @since 02-Jul-2010 */ class ResourceIndexComparator implements Comparator<Capability> { private final XEnvironment environment; ResourceIndexComparator(XEnvironment environment) { this.environment = environment; } XEnvironment getEnvironment() { return environment; } @Override public int compare(Capability o1, Capability o2) {
Long in1 = getResourceIndex((XResource) o1.getResource());
jbosgi/jbosgi-resolver
felix/src/main/java/org/jboss/osgi/resolver/felix/LoggerDelegate.java
// Path: api/src/main/java/org/jboss/osgi/resolver/ResolverLogger.java // @MessageLogger(projectCode = "JBOSGI") // public interface ResolverLogger extends BasicLogger { // // ResolverLogger LOGGER = Logger.getMessageLogger(ResolverLogger.class, "org.jboss.osgi.resolver"); // }
import org.jboss.osgi.resolver.ResolverLogger; import static org.jboss.osgi.resolver.ResolverLogger.LOGGER;
/* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.felix; /** * An integration with the resolver Logger. * * This Logger delegates framework log messages to JBoss Logging. * * @author thomas.diesler@jboss.com * @since 14-Feb-2012 */ public class LoggerDelegate extends org.apache.felix.resolver.Logger { public LoggerDelegate() {
// Path: api/src/main/java/org/jboss/osgi/resolver/ResolverLogger.java // @MessageLogger(projectCode = "JBOSGI") // public interface ResolverLogger extends BasicLogger { // // ResolverLogger LOGGER = Logger.getMessageLogger(ResolverLogger.class, "org.jboss.osgi.resolver"); // } // Path: felix/src/main/java/org/jboss/osgi/resolver/felix/LoggerDelegate.java import org.jboss.osgi.resolver.ResolverLogger; import static org.jboss.osgi.resolver.ResolverLogger.LOGGER; /* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.felix; /** * An integration with the resolver Logger. * * This Logger delegates framework log messages to JBoss Logging. * * @author thomas.diesler@jboss.com * @since 14-Feb-2012 */ public class LoggerDelegate extends org.apache.felix.resolver.Logger { public LoggerDelegate() {
super(getLevel(ResolverLogger.LOGGER));
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/OSGiMetaDataProcessor.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import java.util.List; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.osgi.metadata.OSGiMetaData; import org.jboss.osgi.metadata.OSGiMetaDataBuilder; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Version; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Capability;
private OSGiMetaDataProcessor() { } public static OSGiMetaData loadOsgiMetaData(Module module) { // Get symbolic name & version ModuleIdentifier moduleId = module.getIdentifier(); String symbolicName = moduleId.getName(); Version version; try { version = Version.parseVersion(moduleId.getSlot()); } catch (IllegalArgumentException ex) { version = Version.emptyVersion; } final OSGiMetaDataBuilder builder = OSGiMetaDataBuilder.createBuilder(symbolicName, version); // Add a package capability for every exported path new ModuleExportPackagesCollector(module) { @Override protected void addPackage(String packageName) { builder.addExportPackages(packageName); } }.collectExportPackages(); return builder.getOSGiMetaData(); }
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/OSGiMetaDataProcessor.java import java.util.List; import org.jboss.modules.Module; import org.jboss.modules.ModuleIdentifier; import org.jboss.osgi.metadata.OSGiMetaData; import org.jboss.osgi.metadata.OSGiMetaDataBuilder; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Version; import org.osgi.framework.namespace.PackageNamespace; import org.osgi.resource.Capability; private OSGiMetaDataProcessor() { } public static OSGiMetaData loadOsgiMetaData(Module module) { // Get symbolic name & version ModuleIdentifier moduleId = module.getIdentifier(); String symbolicName = moduleId.getName(); Version version; try { version = Version.parseVersion(moduleId.getSlot()); } catch (IllegalArgumentException ex) { version = Version.emptyVersion; } final OSGiMetaDataBuilder builder = OSGiMetaDataBuilder.createBuilder(symbolicName, version); // Add a package capability for every exported path new ModuleExportPackagesCollector(module) { @Override protected void addPackage(String packageName) { builder.addExportPackages(packageName); } }.collectExportPackages(); return builder.getOSGiMetaData(); }
public static OSGiMetaData getOsgiMetaData(XBundleRevision brev)
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/RequireCapabilityResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.resource.Capability; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XResource;
/* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 20-Nov-2012 */ public class RequireCapabilityResolverTest extends AbstractResolverTest { @Test public void testNamespaceValueInFilter() throws Exception {
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/RequireCapabilityResolverTest.java import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.framework.Version; import org.osgi.resource.Capability; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.junit.Assert; import org.jboss.osgi.metadata.OSGiManifestBuilder; import org.jboss.osgi.resolver.XResource; /* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 20-Nov-2012 */ public class RequireCapabilityResolverTest extends AbstractResolverTest { @Test public void testNamespaceValueInFilter() throws Exception {
XResource resourceA = createResource(getArchiveA());
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/PreferencesResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.jboss.shrinkwrap.api.Archive; import org.junit.Test; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XResource;
/* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @author <a href="david@redhat.com">David Bosschaert</a> * @since 31-May-2010 */ public class PreferencesResolverTest extends AbstractResolverTest { @Test public void testPreferredExporterResolved() throws Exception { // Bundle-SymbolicName: simpleimport // Import-Package: org.jboss.test.osgi.classloader.support.a Archive<?> assemblyA = assembleArchive("resourceA", "/resolver/simpleimport");
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/PreferencesResolverTest.java import org.jboss.shrinkwrap.api.Archive; import org.junit.Test; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XResource; /* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @author <a href="david@redhat.com">David Bosschaert</a> * @since 31-May-2010 */ public class PreferencesResolverTest extends AbstractResolverTest { @Test public void testPreferredExporterResolved() throws Exception { // Bundle-SymbolicName: simpleimport // Import-Package: org.jboss.test.osgi.classloader.support.a Archive<?> assemblyA = assembleArchive("resourceA", "/resolver/simpleimport");
XResource resourceA = createResource(assemblyA);
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire;
package org.jboss.osgi.resolver.spi; /* * #%L * JBossOSGi Framework * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * The {@link BundleWire} implementation. * * @author thomas.diesler@jboss.com * @since 23-Feb-2012 */ public class AbstractBundleWire extends AbstractWire implements BundleWire { public AbstractBundleWire(Wire wire) { super(wire.getCapability(), wire.getRequirement(), wire.getProvider(), wire.getRequirer()); } public AbstractBundleWire(BundleCapability cap, BundleRequirement req, BundleRevision provider, BundleRevision requirer) { super(cap, req, provider, requirer); } @Override public BundleWiring getProviderWiring() { return getProviderWiring(true); } @Override public BundleWiring getRequirerWiring() { return getRequirerWiring(true); } public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; }
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire; package org.jboss.osgi.resolver.spi; /* * #%L * JBossOSGi Framework * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /** * The {@link BundleWire} implementation. * * @author thomas.diesler@jboss.com * @since 23-Feb-2012 */ public class AbstractBundleWire extends AbstractWire implements BundleWire { public AbstractBundleWire(Wire wire) { super(wire.getCapability(), wire.getRequirement(), wire.getProvider(), wire.getRequirer()); } public AbstractBundleWire(BundleCapability cap, BundleRequirement req, BundleRevision provider, BundleRevision requirer) { super(cap, req, provider, requirer); } @Override public BundleWiring getProviderWiring() { return getProviderWiring(true); } @Override public BundleWiring getRequirerWiring() { return getRequirerWiring(true); } public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; }
public XBundleRevision getProvider() {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire;
@Override public BundleWiring getRequirerWiring() { return getRequirerWiring(true); } public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; } public XBundleRevision getProvider() { return (XBundleRevision) super.getProvider(); } public XBundleRevision getRequirer() { return (XBundleRevision) super.getRequirer(); } @Override
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire; @Override public BundleWiring getRequirerWiring() { return getRequirerWiring(true); } public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; } public XBundleRevision getProvider() { return (XBundleRevision) super.getProvider(); } public XBundleRevision getRequirer() { return (XBundleRevision) super.getRequirer(); } @Override
public XBundleCapability getCapability() {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire;
public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; } public XBundleRevision getProvider() { return (XBundleRevision) super.getProvider(); } public XBundleRevision getRequirer() { return (XBundleRevision) super.getRequirer(); } @Override public XBundleCapability getCapability() { return (XBundleCapability) super.getCapability(); } @Override
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRequirement.java // public interface XBundleRequirement extends XRequirement, BundleRequirement { // // /** // * Get the bundle revision declaring this requirement. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this requirement. // */ // XBundleRevision getRevision(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleWire.java import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRequirement; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWire; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Wire; public BundleWiring getProviderWiring(boolean checkInUse) { BundleWiring providerWiring = (BundleWiring) super.getProviderWiring(); if (providerWiring != null) { return !checkInUse || providerWiring.isInUse() ? providerWiring : null; } return null; } public BundleWiring getRequirerWiring(boolean checkInUse) { BundleWiring requirerWiring = (BundleWiring) super.getRequirerWiring(); if (requirerWiring != null) { return !checkInUse || requirerWiring.isInUse() ? requirerWiring : null; } return null; } public XBundleRevision getProvider() { return (XBundleRevision) super.getProvider(); } public XBundleRevision getRequirer() { return (XBundleRevision) super.getRequirer(); } @Override public XBundleCapability getCapability() { return (XBundleCapability) super.getCapability(); } @Override
public XBundleRequirement getRequirement() {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/XResolver.java
// Path: api/src/main/java/org/osgi/service/resolver/ResolutionException.java // public class ResolutionException extends Exception { // // private static final long serialVersionUID = 1L; // // private transient final Collection<Requirement> unresolvedRequirements; // // /** // * Create a {@code ResolutionException} with the specified message, cause // * and unresolved requirements. // * // * @param message The message. // * @param cause The cause of this exception. // * @param unresolvedRequirements The unresolved mandatory requirements from // * mandatory resources or {@code null} if no unresolved requirements // * information is provided. // */ // public ResolutionException(String message, Throwable cause, Collection<Requirement> unresolvedRequirements) { // super(message, cause); // if ((unresolvedRequirements == null) || unresolvedRequirements.isEmpty()) { // this.unresolvedRequirements = emptyCollection(); // } else { // this.unresolvedRequirements = Collections.unmodifiableCollection(new ArrayList<Requirement>(unresolvedRequirements)); // } // } // // /** // * Create a {@code ResolutionException} with the specified message. // * // * @param message The message. // */ // public ResolutionException(String message) { // super(message); // unresolvedRequirements = emptyCollection(); // } // // /** // * Create a {@code ResolutionException} with the specified cause. // * // * @param cause The cause of this exception. // */ // public ResolutionException(Throwable cause) { // super(cause); // unresolvedRequirements = emptyCollection(); // } // // @SuppressWarnings("unchecked") // private static <T> Collection<T> emptyCollection() { // return Collections.EMPTY_LIST; // } // // /** // * Return the unresolved requirements, if any, for this exception. // * // * <p> // * The unresolved requirements are provided for informational purposes and // * the specific set of unresolved requirements that are provided after a // * resolve failure is not defined. // * // * @return A collection of the unresolved requirements for this exception. // * The returned collection may be empty if no unresolved // * requirements information is provided. // */ // public Collection<Requirement> getUnresolvedRequirements() { // return unresolvedRequirements; // } // }
import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.service.resolver.ResolutionException; import org.osgi.service.resolver.Resolver;
/* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver; /** * An extension of the {@link Resolver} * * @author thomas.diesler@jboss.com * @since 02-Apr-2012 */ public interface XResolver extends Resolver { XResolveContext createResolveContext(XEnvironment environment, Collection<? extends Resource> mandatory, Collection<? extends Resource> optional);
// Path: api/src/main/java/org/osgi/service/resolver/ResolutionException.java // public class ResolutionException extends Exception { // // private static final long serialVersionUID = 1L; // // private transient final Collection<Requirement> unresolvedRequirements; // // /** // * Create a {@code ResolutionException} with the specified message, cause // * and unresolved requirements. // * // * @param message The message. // * @param cause The cause of this exception. // * @param unresolvedRequirements The unresolved mandatory requirements from // * mandatory resources or {@code null} if no unresolved requirements // * information is provided. // */ // public ResolutionException(String message, Throwable cause, Collection<Requirement> unresolvedRequirements) { // super(message, cause); // if ((unresolvedRequirements == null) || unresolvedRequirements.isEmpty()) { // this.unresolvedRequirements = emptyCollection(); // } else { // this.unresolvedRequirements = Collections.unmodifiableCollection(new ArrayList<Requirement>(unresolvedRequirements)); // } // } // // /** // * Create a {@code ResolutionException} with the specified message. // * // * @param message The message. // */ // public ResolutionException(String message) { // super(message); // unresolvedRequirements = emptyCollection(); // } // // /** // * Create a {@code ResolutionException} with the specified cause. // * // * @param cause The cause of this exception. // */ // public ResolutionException(Throwable cause) { // super(cause); // unresolvedRequirements = emptyCollection(); // } // // @SuppressWarnings("unchecked") // private static <T> Collection<T> emptyCollection() { // return Collections.EMPTY_LIST; // } // // /** // * Return the unresolved requirements, if any, for this exception. // * // * <p> // * The unresolved requirements are provided for informational purposes and // * the specific set of unresolved requirements that are provided after a // * resolve failure is not defined. // * // * @return A collection of the unresolved requirements for this exception. // * The returned collection may be empty if no unresolved // * requirements information is provided. // */ // public Collection<Requirement> getUnresolvedRequirements() { // return unresolvedRequirements; // } // } // Path: api/src/main/java/org/jboss/osgi/resolver/XResolver.java import java.util.Collection; import java.util.List; import java.util.Map; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import org.osgi.service.resolver.ResolutionException; import org.osgi.service.resolver.Resolver; /* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver; /** * An extension of the {@link Resolver} * * @author thomas.diesler@jboss.com * @since 02-Apr-2012 */ public interface XResolver extends Resolver { XResolveContext createResolveContext(XEnvironment environment, Collection<? extends Resource> mandatory, Collection<? extends Resource> optional);
Map<Resource, List<Wire>> resolveAndApply(XResolveContext context) throws ResolutionException;
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleCapability.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRevision; import org.jboss.osgi.resolver.XResource; import java.util.Map;
/* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * The abstract implementation of an {@link XBundleCapability}. * * @author thomas.diesler@jboss.com * @since 30-May-2012 */ public class AbstractBundleCapability extends AbstractCapability implements XBundleCapability { public AbstractBundleCapability(XResource resource, String namespace, Map<String, Object> atts, Map<String, String> dirs) { super(resource, namespace, atts, dirs); } @Override
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundleCapability.java // public interface XBundleCapability extends XCapability, BundleCapability { // // /** // * Get the bundle revision declaring this capability. // */ // XBundleRevision getResource(); // // /** // * Get the bundle revision this capability. // */ // XBundleRevision getRevision(); // // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractBundleCapability.java import org.jboss.osgi.resolver.XBundleCapability; import org.jboss.osgi.resolver.XBundleRevision; import org.jboss.osgi.resolver.XResource; import java.util.Map; /* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * The abstract implementation of an {@link XBundleCapability}. * * @author thomas.diesler@jboss.com * @since 30-May-2012 */ public class AbstractBundleCapability extends AbstractCapability implements XBundleCapability { public AbstractBundleCapability(XResource resource, String namespace, Map<String, Object> atts, Map<String, String> dirs) { super(resource, namespace, atts, dirs); } @Override
public XBundleRevision getResource() {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // }
import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability;
synchronized (this) { // Necessary to guard collections post-construction if (reqwires != null) { for (Wire wire : reqwires) { addRequiredWire(wire); } } if (provwires != null) { for (Wire wire : provwires) { addProvidedWire(wire); } } } } @Override public XResource getResource() { return resource; } @Override public boolean isEffective() { return resource.getWiringSupport().isEffective(); } @Override public void addRequiredWire(Wire wire) { synchronized (required) { if (wire instanceof AbstractWire) {
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability; synchronized (this) { // Necessary to guard collections post-construction if (reqwires != null) { for (Wire wire : reqwires) { addRequiredWire(wire); } } if (provwires != null) { for (Wire wire : provwires) { addProvidedWire(wire); } } } } @Override public XResource getResource() { return resource; } @Override public boolean isEffective() { return resource.getWiringSupport().isEffective(); } @Override public void addRequiredWire(Wire wire) { synchronized (required) { if (wire instanceof AbstractWire) {
((XWire) wire).setRequirerWiring(this);
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // }
import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability;
} } private int getCapabilityIndex(Capability cap) { return getResource().getCapabilities(cap.getNamespace()).indexOf(cap); } @Override public List<Capability> getResourceCapabilities(String namespace) { List<Capability> result = new ArrayList<Capability>(resource.getCapabilities(namespace)); synchronized (this) { // Add capabilities from attached fragments for (Wire wire : getProvidedResourceWires(HostNamespace.HOST_NAMESPACE)) { for (Capability cap : wire.getRequirer().getCapabilities(namespace)) { // The osgi.identity capability provided by attached // fragment // must not be included in the capabilities of the host // wiring if (IDENTITY_NAMESPACE.equals(cap.getNamespace())) { continue; } result.add(cap); } } } // Remove unwanted caps Iterator<Capability> capit = result.iterator(); while (capit.hasNext()) { boolean removed = false;
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability; } } private int getCapabilityIndex(Capability cap) { return getResource().getCapabilities(cap.getNamespace()).indexOf(cap); } @Override public List<Capability> getResourceCapabilities(String namespace) { List<Capability> result = new ArrayList<Capability>(resource.getCapabilities(namespace)); synchronized (this) { // Add capabilities from attached fragments for (Wire wire : getProvidedResourceWires(HostNamespace.HOST_NAMESPACE)) { for (Capability cap : wire.getRequirer().getCapabilities(namespace)) { // The osgi.identity capability provided by attached // fragment // must not be included in the capabilities of the host // wiring if (IDENTITY_NAMESPACE.equals(cap.getNamespace())) { continue; } result.add(cap); } } } // Remove unwanted caps Iterator<Capability> capit = result.iterator(); while (capit.hasNext()) { boolean removed = false;
XCapability cap = (XCapability) capit.next();
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // }
import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability;
} // Remove identity capability for fragments String type = res.getIdentityCapability().getType(); if (!removed && IDENTITY_NAMESPACE.equals(cap.getNamespace()) && XResource.TYPE_FRAGMENT.equals(type)) { capit.remove(); removed = true; } } return Collections.unmodifiableList(result); } protected HostedCapability getHostedCapability(XCapability cap) { return new AbstractHostedCapability(resource, cap); } @Override public List<Requirement> getResourceRequirements(String namespace) { List<Requirement> result = new ArrayList<Requirement>(); synchronized (this) { for (Wire wire : getRequiredResourceWires(namespace)) { // A fragment may have multiple wire for the same host // requirement Requirement req = wire.getRequirement(); if (!result.contains(req)) { result.add(req); } } // Add dynamic package requirements that are not included already for (Requirement req : getResource().getRequirements(namespace)) {
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageRequirement.java // public interface XPackageRequirement extends XRequirement { // // /** // * The package name // */ // String getPackageName(); // // /** // * A flag indicating that this is a dynamic package requirement // */ // boolean isDynamic(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWire.java // public interface XWire extends Wire { // // Wiring getProviderWiring(); // // void setProviderWiring(Wiring providerWiring); // // Wiring getRequirerWiring(); // // void setRequirerWiring(Wiring requirerWiring); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XWiring.java // public interface XWiring extends Wiring { // // boolean isEffective(); // // void addRequiredWire(Wire wire); // // void addProvidedWire(Wire wire); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractWiring.java import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.IdentityNamespace.IDENTITY_NAMESPACE; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageRequirement; import org.jboss.osgi.resolver.XResource; import org.jboss.osgi.resolver.XWire; import org.jboss.osgi.resolver.XWiring; import org.osgi.framework.namespace.HostNamespace; import org.osgi.resource.Capability; import org.osgi.resource.Namespace; import org.osgi.resource.Requirement; import org.osgi.resource.Wire; import org.osgi.resource.Wiring; import org.osgi.service.resolver.HostedCapability; } // Remove identity capability for fragments String type = res.getIdentityCapability().getType(); if (!removed && IDENTITY_NAMESPACE.equals(cap.getNamespace()) && XResource.TYPE_FRAGMENT.equals(type)) { capit.remove(); removed = true; } } return Collections.unmodifiableList(result); } protected HostedCapability getHostedCapability(XCapability cap) { return new AbstractHostedCapability(resource, cap); } @Override public List<Requirement> getResourceRequirements(String namespace) { List<Requirement> result = new ArrayList<Requirement>(); synchronized (this) { for (Wire wire : getRequiredResourceWires(namespace)) { // A fragment may have multiple wire for the same host // requirement Requirement req = wire.getRequirement(); if (!result.contains(req)) { result.add(req); } } // Add dynamic package requirements that are not included already for (Requirement req : getResource().getRequirements(namespace)) {
if (req instanceof XPackageRequirement) {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/AbstractHostedCapability.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XResource; import org.osgi.resource.Capability; import org.osgi.service.resolver.HostedCapability;
@Override public Map<String, String> getDirectives() { return capability.getDirectives(); } @Override public Map<String, Object> getAttributes() { return capability.getAttributes(); } @Override public Object getAttribute(String key) { return capability.getAttribute(key); } @Override public String getDirective(String key) { return capability.getDirective(key); } @Override public void validate() { capability.validate(); } @Override @SuppressWarnings("unchecked") public <T extends XCapability> T adapt(Class<T> clazz) { T result = null;
// Path: api/src/main/java/org/jboss/osgi/resolver/XCapability.java // public interface XCapability extends XElement, XAttributeSupport, XDirectiveSupport, Capability { // // /** // * Get the resource declaring this capability. // */ // XResource getResource(); // // /** // * Validate the capability // */ // void validate(); // // /** // * Adapt this capability to another type // */ // <T extends XCapability> T adapt(Class<T> clazz); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XPackageCapability.java // public interface XPackageCapability extends XCapability { // // /** // * The package name // */ // String getPackageName(); // // /** // * The package version. // */ // Version getVersion(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/AbstractHostedCapability.java import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import static org.osgi.framework.namespace.PackageNamespace.PACKAGE_NAMESPACE; import java.util.Map; import org.jboss.osgi.resolver.XCapability; import org.jboss.osgi.resolver.XPackageCapability; import org.jboss.osgi.resolver.XResource; import org.osgi.resource.Capability; import org.osgi.service.resolver.HostedCapability; @Override public Map<String, String> getDirectives() { return capability.getDirectives(); } @Override public Map<String, Object> getAttributes() { return capability.getAttributes(); } @Override public Object getAttribute(String key) { return capability.getAttribute(key); } @Override public String getDirective(String key) { return capability.getDirective(key); } @Override public void validate() { capability.validate(); } @Override @SuppressWarnings("unchecked") public <T extends XCapability> T adapt(Class<T> clazz) { T result = null;
if (XPackageCapability.class == clazz && PACKAGE_NAMESPACE.equals(getNamespace())) {
jbosgi/jbosgi-resolver
felix/src/test/java/org/jboss/test/osgi/resolver/DynamicPackageImportResolverTest.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // }
import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Map; import org.jboss.osgi.metadata.OSGiManifestBuilder;
/* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 25-Feb-2012 */ public class DynamicPackageImportResolverTest extends AbstractResolverTest { @Test public void testBundleSymbolicNameDirective() throws Exception { final JavaArchive archiveA = ShrinkWrap.create(JavaArchive.class, "tb8a"); archiveA.setManifest(new Asset() { public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName(archiveA.getName()); builder.addExportPackages("org.jboss.test.osgi.framework.classloader.support.a"); return builder.openStream(); } });
// Path: api/src/main/java/org/jboss/osgi/resolver/XResource.java // public interface XResource extends XElement, XAttributeSupport, Resource { // // /** The id attachment key */ // AttachmentKey<Long> RESOURCE_IDENTIFIER_KEY = AttachmentKey.create(Long.class); // // /** // * Artifact coordinates may be defined by the simple groupId:artifactId:version form, // * or the fully qualified form groupId:artifactId:type:version[:classifier] // */ // String MAVEN_IDENTITY_NAMESPACE = "maven.identity"; // // /** // * Artifact coordinates are defined by {@link org.jboss.modules.ModuleIdentifier} // */ // String MODULE_IDENTITY_NAMESPACE = "module.identity"; // // /** // * The attribute on the {@link XIdentityCapability} for the below types // */ // String CAPABILITY_TYPE_ATTRIBUTE = IdentityNamespace.CAPABILITY_TYPE_ATTRIBUTE; // // /** // * Some predefined resource types // */ // String TYPE_BUNDLE = IdentityNamespace.TYPE_BUNDLE; // String TYPE_FRAGMENT = IdentityNamespace.TYPE_FRAGMENT; // String TYPE_UNKNOWN = IdentityNamespace.TYPE_UNKNOWN; // String TYPE_ABSTRACT = "abstract"; // String TYPE_MODULE = "module"; // String TYPE_MAVEN = "maven"; // // /** // * Get the identity capability for this resource // */ // XIdentityCapability getIdentityCapability(); // // /** // * Validate the resource // */ // void validate(); // // /** // * Get the current resource state // */ // State getState(); // // /** // * True if the resource is mutable // */ // boolean isMutable(); // // /** // * True if the resource is abstract // */ // boolean isAbstract(); // // /** // * Make the resource immutable // */ // void setMutable(boolean mutable); // // /** // * Get the {@link XWiringSupport} associated with this resource // */ // XWiringSupport getWiringSupport(); // // /** // * Get the {@link XWiring} associated with this resource // */ // XWiring getWiring(boolean checkEffective); // // /** // * The resource state in the {@link XEnvironment} // */ // enum State { // INSTALLED, UNINSTALLED // } // } // Path: felix/src/test/java/org/jboss/test/osgi/resolver/DynamicPackageImportResolverTest.java import org.jboss.osgi.resolver.XResource; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.osgi.resource.Resource; import org.osgi.resource.Wire; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.Map; import org.jboss.osgi.metadata.OSGiManifestBuilder; /* * #%L * JBossOSGi Resolver Felix * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.test.osgi.resolver; /** * Test the default resolver integration. * * @author thomas.diesler@jboss.com * @since 25-Feb-2012 */ public class DynamicPackageImportResolverTest extends AbstractResolverTest { @Test public void testBundleSymbolicNameDirective() throws Exception { final JavaArchive archiveA = ShrinkWrap.create(JavaArchive.class, "tb8a"); archiveA.setManifest(new Asset() { public InputStream openStream() { OSGiManifestBuilder builder = OSGiManifestBuilder.newInstance(); builder.addBundleManifestVersion(2); builder.addBundleSymbolicName(archiveA.getName()); builder.addExportPackages("org.jboss.test.osgi.framework.classloader.support.a"); return builder.openStream(); } });
XResource resourceA = createResource(archiveA);
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/ResolverHookProcessor.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundle.java // public interface XBundle extends Attachable, Bundle { // // /** // * Get the current {@link XBundleRevision} // */ // XBundleRevision getBundleRevision(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * True if the bundle is resolved. // */ // boolean isResolved(); // // /** // * True if the bundle is a fragment. // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import static org.jboss.osgi.resolver.ResolverLogger.LOGGER; import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XBundle; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Resource;
/* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * The default implementation for {@link ResolverHook} functionality. * * @author thomas.diesler@jboss.com * @since 01-Feb-2013 */ public class ResolverHookProcessor { private static ThreadLocal<ResolverHookProcessor> processorAssociation = new ThreadLocal<ResolverHookProcessor>(); private final BundleContext syscontext; private List<ResolverHookRegistration> registrations; private Collection<BundleRevision> candidates; public interface SingletonLocator { Collection<BundleCapability> findCollisionCandidates(BundleCapability icap); }
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundle.java // public interface XBundle extends Attachable, Bundle { // // /** // * Get the current {@link XBundleRevision} // */ // XBundleRevision getBundleRevision(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * True if the bundle is resolved. // */ // boolean isResolved(); // // /** // * True if the bundle is a fragment. // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/ResolverHookProcessor.java import static org.jboss.osgi.resolver.ResolverLogger.LOGGER; import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XBundle; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Resource; /* * #%L * JBossOSGi Resolver API * %% * Copyright (C) 2010 - 2012 JBoss by Red Hat * %% * 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. * #L% */ package org.jboss.osgi.resolver.spi; /** * The default implementation for {@link ResolverHook} functionality. * * @author thomas.diesler@jboss.com * @since 01-Feb-2013 */ public class ResolverHookProcessor { private static ThreadLocal<ResolverHookProcessor> processorAssociation = new ThreadLocal<ResolverHookProcessor>(); private final BundleContext syscontext; private List<ResolverHookRegistration> registrations; private Collection<BundleRevision> candidates; public interface SingletonLocator { Collection<BundleCapability> findCollisionCandidates(BundleCapability icap); }
public ResolverHookProcessor(BundleContext syscontext, Collection<XBundle> unresolved) {
jbosgi/jbosgi-resolver
api/src/main/java/org/jboss/osgi/resolver/spi/ResolverHookProcessor.java
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundle.java // public interface XBundle extends Attachable, Bundle { // // /** // * Get the current {@link XBundleRevision} // */ // XBundleRevision getBundleRevision(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * True if the bundle is resolved. // */ // boolean isResolved(); // // /** // * True if the bundle is a fragment. // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // }
import static org.jboss.osgi.resolver.ResolverLogger.LOGGER; import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XBundle; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Resource;
public void begin(Collection<? extends Resource> mandatory, Collection<? extends Resource> optional) { // Set the thread association processorAssociation.set(this); // Get the initial set of trigger bundles Collection<BundleRevision> triggers = new ArrayList<BundleRevision>(); addTriggers(mandatory, triggers); addTriggers(optional, triggers); triggers = new RemoveOnlyCollection<BundleRevision>(triggers); // Create a {@link ResolverHook} for each factory if (registrations != null) { for (ResolverHookRegistration hookreg : registrations) { try { ResolverHookFactory hookFactory = syscontext.getService(hookreg.sref); if (hookreg.isRegistered()) { hookreg.hook = hookFactory.begin(triggers); } } catch (RuntimeException ex) { hookreg.lastException = ex; throw new ResolverHookException(ex); } } } } private void addTriggers(Collection<? extends Resource> resources, Collection<BundleRevision> triggers) { if (resources != null) { for (Resource res : resources) {
// Path: api/src/main/java/org/jboss/osgi/resolver/XBundle.java // public interface XBundle extends Attachable, Bundle { // // /** // * Get the current {@link XBundleRevision} // */ // XBundleRevision getBundleRevision(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * True if the bundle is resolved. // */ // boolean isResolved(); // // /** // * True if the bundle is a fragment. // */ // boolean isFragment(); // } // // Path: api/src/main/java/org/jboss/osgi/resolver/XBundleRevision.java // public interface XBundleRevision extends XResource, BundleRevision { // // /** // * Get the associated {@link XBundle} // */ // XBundle getBundle(); // // /** // * Get the {@link XBundleWiringSupport} associated with this resource // */ // XBundleWiringSupport getWiringSupport(); // // /** // * Get the bundle canonical name // * // * [symbolicName:version] // */ // String getCanonicalName(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleIdentifier getModuleIdentifier(); // // /** // * Get the associated {@link ModuleIdentifier} // * or null if the revision is not resolved // */ // ModuleClassLoader getModuleClassLoader(); // // /** // * @see {@link Bundle#getResource(String)} // */ // URL getResource(String name); // // /** // * @see {@link Bundle#getResources(String)} // */ // Enumeration<URL> getResources(String name) throws IOException; // // /** // * @see {@link Bundle#findEntries(String, String, boolean)} // */ // Enumeration<URL> findEntries(String path, String filePattern, boolean recursive); // // /** // * @see {@link Bundle#getEntry(String)} // */ // URL getEntry(String path); // // /** // * @see {@link Bundle#getEntryPaths(String)} // */ // Enumeration<String> getEntryPaths(String path); // // /** // * True if this revision is a fragment // */ // boolean isFragment(); // } // Path: api/src/main/java/org/jboss/osgi/resolver/spi/ResolverHookProcessor.java import static org.jboss.osgi.resolver.ResolverLogger.LOGGER; import static org.jboss.osgi.resolver.ResolverMessages.MESSAGES; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import org.jboss.osgi.resolver.XBundle; import org.jboss.osgi.resolver.XBundleRevision; import org.osgi.framework.Bundle; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.osgi.framework.hooks.resolver.ResolverHook; import org.osgi.framework.hooks.resolver.ResolverHookFactory; import org.osgi.framework.namespace.IdentityNamespace; import org.osgi.framework.wiring.BundleCapability; import org.osgi.framework.wiring.BundleRequirement; import org.osgi.framework.wiring.BundleRevision; import org.osgi.framework.wiring.BundleWiring; import org.osgi.resource.Resource; public void begin(Collection<? extends Resource> mandatory, Collection<? extends Resource> optional) { // Set the thread association processorAssociation.set(this); // Get the initial set of trigger bundles Collection<BundleRevision> triggers = new ArrayList<BundleRevision>(); addTriggers(mandatory, triggers); addTriggers(optional, triggers); triggers = new RemoveOnlyCollection<BundleRevision>(triggers); // Create a {@link ResolverHook} for each factory if (registrations != null) { for (ResolverHookRegistration hookreg : registrations) { try { ResolverHookFactory hookFactory = syscontext.getService(hookreg.sref); if (hookreg.isRegistered()) { hookreg.hook = hookFactory.begin(triggers); } } catch (RuntimeException ex) { hookreg.lastException = ex; throw new ResolverHookException(ex); } } } } private void addTriggers(Collection<? extends Resource> resources, Collection<BundleRevision> triggers) { if (resources != null) { for (Resource res : resources) {
XBundleRevision brev = (XBundleRevision) res;
pfn/keepassj
src/test/java/com/hanhuy/keepassj/PwEntryTestV3.java
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // }
import com.hanhuy.keepassj.database.TestData; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import java.util.Calendar;
package com.hanhuy.keepassj; /* * Copyright 2009 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class PwEntryTestV3 { static PwEntry mPE; @BeforeClass public static void setUp() throws Exception {
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // } // Path: src/test/java/com/hanhuy/keepassj/PwEntryTestV3.java import com.hanhuy.keepassj.database.TestData; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import java.io.UnsupportedEncodingException; import java.util.Calendar; package com.hanhuy.keepassj; /* * Copyright 2009 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class PwEntryTestV3 { static PwEntry mPE; @BeforeClass public static void setUp() throws Exception {
mPE = (PwEntry) TestData.GetTest1().getRootGroup().GetEntries(true).GetAt(0);
pfn/keepassj
src/test/java/com/hanhuy/keepassj/search/SearchTest.java
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // }
import com.hanhuy.keepassj.*; import com.hanhuy.keepassj.database.TestData; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package com.hanhuy.keepassj.search; /* * Copyright 2009-2011 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class SearchTest { private static PwDatabase mDb; @BeforeClass public static void setUp() throws Exception {
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // } // Path: src/test/java/com/hanhuy/keepassj/search/SearchTest.java import com.hanhuy.keepassj.*; import com.hanhuy.keepassj.database.TestData; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package com.hanhuy.keepassj.search; /* * Copyright 2009-2011 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class SearchTest { private static PwDatabase mDb; @BeforeClass public static void setUp() throws Exception {
mDb = TestData.GetDb1(true);
pfn/keepassj
src/test/java/com/hanhuy/keepassj/PwGroupTest.java
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // }
import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.hanhuy.keepassj.database.TestData; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test;
package com.hanhuy.keepassj; /* * Copyright 2009 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class PwGroupTest { static PwGroup mPG; @BeforeClass public static void setUp() throws Exception {
// Path: src/test/java/com/hanhuy/keepassj/database/TestData.java // public class TestData { // public static final String TEST1_KEYFILE = ""; // public static final String TEST1_PASSWORD = "12345"; // public static final String TEST_KDBX = "test.kdbx"; // // public static PwDatabase GetDb1() throws Exception { // return GetDb1(false); // } // // public static PwDatabase GetDb1(boolean forceReload) throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // // public static PwDatabase GetDb(File f, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.Open(IOConnectionInfo.FromPath(f.getAbsolutePath()), key, null); // return Db; // } // public static PwDatabase GetDb(InputStream is, String password, String keyfile) throws Exception { // PwDatabase Db = new PwDatabase(); // CompositeKey key = new CompositeKey(); // key.AddUserKey(new KcpPassword(password)); // if (!Strings.isNullOrEmpty(keyfile)) { // key.AddUserKey(new KcpKeyFile(keyfile)); // } // Db.setMasterKey(key); // KdbxFile file = new KdbxFile(Db); // file.Load(is, KdbxFormat.Default, null); // is.close(); // return Db; // } // // public static PwDatabase GetDb(String asset, String password, String keyfile) throws Exception { // InputStream is = TestData.class.getClassLoader().getResourceAsStream(asset); // return GetDb(is, password, keyfile); // } // // public static PwDatabase GetTest2() throws Exception { // return GetDb1(); // } // // public static PwDatabase GetTest1() throws Exception { // return GetDb(TEST_KDBX, TEST1_PASSWORD, TEST1_KEYFILE); // } // } // Path: src/test/java/com/hanhuy/keepassj/PwGroupTest.java import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.hanhuy.keepassj.database.TestData; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; package com.hanhuy.keepassj; /* * Copyright 2009 Brian Pellin. * * This file is part of KeePassDroid. * * KeePassDroid is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * KeePassDroid is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with KeePassDroid. If not, see <http://www.gnu.org/licenses/>. * */ public class PwGroupTest { static PwGroup mPG; @BeforeClass public static void setUp() throws Exception {
mPG = TestData.GetTest1().getRootGroup().GetGroups(false).GetAt(0);
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/CodeMapping.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/IVariantSyncMarker.java // public interface IVariantSyncMarker { // // /** // * Returns marker id. // * // * @return markerId // */ // long getMarkerId(); // // /** // * Sets marker id. // * // * @param markerId - id of marker // */ // void setMarkerId(long markerId); // // /** // * Returns offset. // * // * @return offset // */ // int getOffset(); // // /** // * Sets offset. // * // * @param offset // */ // void setOffset(int offset); // // /** // * Returns length. // * // * @return length // */ // int getLength(); // // /** // * Sets length. // * // * @param length // */ // void setLength(int length); // // /** // * Returns feature context. // * // * @return feature context // */ // String getContext(); // // /** // * Sets feature expression. // * // * @param context - feature context // */ // void setContext(String context); // // /** // * Returns whether the complete line is annotated // * // * @return true, if the complete line is annotated // */ // boolean isLine(); // // /** // * Sets whether the complete line is annotated // * // * @param true, if the complete line is annotated // */ // void setLine(boolean isLine); // }
import de.tubs.variantsync.core.utilities.IVariantSyncMarker;
package de.tubs.variantsync.core.managers.data; public class CodeMapping { private String code;
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/IVariantSyncMarker.java // public interface IVariantSyncMarker { // // /** // * Returns marker id. // * // * @return markerId // */ // long getMarkerId(); // // /** // * Sets marker id. // * // * @param markerId - id of marker // */ // void setMarkerId(long markerId); // // /** // * Returns offset. // * // * @return offset // */ // int getOffset(); // // /** // * Sets offset. // * // * @param offset // */ // void setOffset(int offset); // // /** // * Returns length. // * // * @return length // */ // int getLength(); // // /** // * Sets length. // * // * @param length // */ // void setLength(int length); // // /** // * Returns feature context. // * // * @return feature context // */ // String getContext(); // // /** // * Sets feature expression. // * // * @param context - feature context // */ // void setContext(String context); // // /** // * Returns whether the complete line is annotated // * // * @return true, if the complete line is annotated // */ // boolean isLine(); // // /** // * Sets whether the complete line is annotated // * // * @param true, if the complete line is annotated // */ // void setLine(boolean isLine); // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/CodeMapping.java import de.tubs.variantsync.core.utilities.IVariantSyncMarker; package de.tubs.variantsync.core.managers.data; public class CodeMapping { private String code;
private IVariantSyncMarker variantSyncMarker;
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/view/featurecontext/FeatureContextWizardPage.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/FeatureContext.java // public class FeatureContext { // // public String name; // public FeatureColor highlighter; // // public FeatureContext() { // this.name = ""; // this.highlighter = FeatureColor.NO_COLOR; // } // // public FeatureContext(String name) { // super(); // this.name = name; // this.highlighter = FeatureColor.Yellow; // } // // public FeatureContext(String name, FeatureColor highlighter) { // super(); // this.name = name; // this.highlighter = highlighter; // } // // public boolean isComposed() { // return name.matches(".*(or|and|not).*"); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((highlighter == null) ? 0 : highlighter.hashCode()); // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // FeatureContext other = (FeatureContext) obj; // if (highlighter != other.highlighter) // return false; // if (name == null) { // if (other.name != null) // return false; // } else if (!name.equals(other.name)) // return false; // return true; // } // // // // }
import static de.ovgu.featureide.fm.core.localization.StringTable.OPERATORS; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TableItem; import de.ovgu.featureide.fm.core.Operator; import de.ovgu.featureide.fm.core.base.FeatureUtils; import de.ovgu.featureide.fm.core.base.IFeature; import de.ovgu.featureide.fm.core.color.ColorPalette; import de.ovgu.featureide.fm.core.color.FeatureColor; import de.ovgu.featureide.fm.core.functional.Functional; import de.ovgu.featureide.fm.ui.editors.SimpleSyntaxHighlightEditor; import de.tubs.variantsync.core.managers.data.FeatureContext;
package de.tubs.variantsync.core.view.featurecontext; /** * Page for {@link FeatureContextManager}. * * @author Christopher Sontag */ public class FeatureContextWizardPage extends WizardPage { protected static final String FILTERTEXT = "Search..."; private final Iterable<IFeature> features; private TableViewer tabFeatures; private StyledText txtSearch; private SimpleSyntaxHighlightEditor txtContext;
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/FeatureContext.java // public class FeatureContext { // // public String name; // public FeatureColor highlighter; // // public FeatureContext() { // this.name = ""; // this.highlighter = FeatureColor.NO_COLOR; // } // // public FeatureContext(String name) { // super(); // this.name = name; // this.highlighter = FeatureColor.Yellow; // } // // public FeatureContext(String name, FeatureColor highlighter) { // super(); // this.name = name; // this.highlighter = highlighter; // } // // public boolean isComposed() { // return name.matches(".*(or|and|not).*"); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((highlighter == null) ? 0 : highlighter.hashCode()); // result = prime * result + ((name == null) ? 0 : name.hashCode()); // return result; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) // return true; // if (obj == null) // return false; // if (getClass() != obj.getClass()) // return false; // FeatureContext other = (FeatureContext) obj; // if (highlighter != other.highlighter) // return false; // if (name == null) { // if (other.name != null) // return false; // } else if (!name.equals(other.name)) // return false; // return true; // } // // // // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/view/featurecontext/FeatureContextWizardPage.java import static de.ovgu.featureide.fm.core.localization.StringTable.OPERATORS; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.eclipse.jface.viewers.ArrayContentProvider; import org.eclipse.jface.viewers.CellLabelProvider; import org.eclipse.jface.viewers.TableViewer; import org.eclipse.jface.viewers.TableViewerColumn; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerCell; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.jface.wizard.WizardPage; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.TableItem; import de.ovgu.featureide.fm.core.Operator; import de.ovgu.featureide.fm.core.base.FeatureUtils; import de.ovgu.featureide.fm.core.base.IFeature; import de.ovgu.featureide.fm.core.color.ColorPalette; import de.ovgu.featureide.fm.core.color.FeatureColor; import de.ovgu.featureide.fm.core.functional.Functional; import de.ovgu.featureide.fm.ui.editors.SimpleSyntaxHighlightEditor; import de.tubs.variantsync.core.managers.data.FeatureContext; package de.tubs.variantsync.core.view.featurecontext; /** * Page for {@link FeatureContextManager}. * * @author Christopher Sontag */ public class FeatureContextWizardPage extends WizardPage { protected static final String FILTERTEXT = "Search..."; private final Iterable<IFeature> features; private TableViewer tabFeatures; private StyledText txtSearch; private SimpleSyntaxHighlightEditor txtContext;
private FeatureContext featureContext = null;
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDeltaFactory.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/exceptions/DiffException.java // public class DiffException extends Exception { // // public DiffException(String message) { // super(message); // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDelta.java // public enum DELTATYPE { // /** An addition was made */ // ADDED, // /** An deletion was made */ // REMOVED, // /** A change was made */ // CHANGED // }
import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFileState; import de.ovgu.featureide.fm.core.IExtension; import de.tubs.variantsync.core.exceptions.DiffException; import de.tubs.variantsync.core.patch.interfaces.IDelta.DELTATYPE;
package de.tubs.variantsync.core.patch.interfaces; /** * Factory to create patches from files * * @author Christopher Sontag * @version 1.0 * @since 15.08.2017 * @param <T> file element, e.g. line, ast element, ... */ public interface IDeltaFactory<T> extends IExtension { public static String extensionPointID = "DeltaFactory"; public static String extensionID = "deltaFactory"; String getName(); /** * Creates a empty delta object * * @param res * @return */ IDelta<T> createDelta(IFile file); /** * Creates a delta object for a resource * * @param res - resource * @param timestamp - timestamp * @param kind - type of change * @return patch object */
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/exceptions/DiffException.java // public class DiffException extends Exception { // // public DiffException(String message) { // super(message); // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDelta.java // public enum DELTATYPE { // /** An addition was made */ // ADDED, // /** An deletion was made */ // REMOVED, // /** A change was made */ // CHANGED // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDeltaFactory.java import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFileState; import de.ovgu.featureide.fm.core.IExtension; import de.tubs.variantsync.core.exceptions.DiffException; import de.tubs.variantsync.core.patch.interfaces.IDelta.DELTATYPE; package de.tubs.variantsync.core.patch.interfaces; /** * Factory to create patches from files * * @author Christopher Sontag * @version 1.0 * @since 15.08.2017 * @param <T> file element, e.g. line, ast element, ... */ public interface IDeltaFactory<T> extends IExtension { public static String extensionPointID = "DeltaFactory"; public static String extensionID = "deltaFactory"; String getName(); /** * Creates a empty delta object * * @param res * @return */ IDelta<T> createDelta(IFile file); /** * Creates a delta object for a resource * * @param res - resource * @param timestamp - timestamp * @param kind - type of change * @return patch object */
List<IDelta<T>> createDeltas(IFile file, long timestamp, DELTATYPE kind) throws DiffException;
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDeltaFactory.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/exceptions/DiffException.java // public class DiffException extends Exception { // // public DiffException(String message) { // super(message); // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDelta.java // public enum DELTATYPE { // /** An addition was made */ // ADDED, // /** An deletion was made */ // REMOVED, // /** A change was made */ // CHANGED // }
import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFileState; import de.ovgu.featureide.fm.core.IExtension; import de.tubs.variantsync.core.exceptions.DiffException; import de.tubs.variantsync.core.patch.interfaces.IDelta.DELTATYPE;
package de.tubs.variantsync.core.patch.interfaces; /** * Factory to create patches from files * * @author Christopher Sontag * @version 1.0 * @since 15.08.2017 * @param <T> file element, e.g. line, ast element, ... */ public interface IDeltaFactory<T> extends IExtension { public static String extensionPointID = "DeltaFactory"; public static String extensionID = "deltaFactory"; String getName(); /** * Creates a empty delta object * * @param res * @return */ IDelta<T> createDelta(IFile file); /** * Creates a delta object for a resource * * @param res - resource * @param timestamp - timestamp * @param kind - type of change * @return patch object */
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/exceptions/DiffException.java // public class DiffException extends Exception { // // public DiffException(String message) { // super(message); // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDelta.java // public enum DELTATYPE { // /** An addition was made */ // ADDED, // /** An deletion was made */ // REMOVED, // /** A change was made */ // CHANGED // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IDeltaFactory.java import java.util.List; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFileState; import de.ovgu.featureide.fm.core.IExtension; import de.tubs.variantsync.core.exceptions.DiffException; import de.tubs.variantsync.core.patch.interfaces.IDelta.DELTATYPE; package de.tubs.variantsync.core.patch.interfaces; /** * Factory to create patches from files * * @author Christopher Sontag * @version 1.0 * @since 15.08.2017 * @param <T> file element, e.g. line, ast element, ... */ public interface IDeltaFactory<T> extends IExtension { public static String extensionPointID = "DeltaFactory"; public static String extensionID = "deltaFactory"; String getName(); /** * Creates a empty delta object * * @param res * @return */ IDelta<T> createDelta(IFile file); /** * Creates a delta object for a resource * * @param res - resource * @param timestamp - timestamp * @param kind - type of change * @return patch object */
List<IDelta<T>> createDeltas(IFile file, long timestamp, DELTATYPE kind) throws DiffException;
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/VariantSyncComposer.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/persistence/FeatureContextFormat.java // public class FeatureContextFormat extends AXMLFormat<List<FeatureContext>> { // // private static final String ID = "FeatureContexts"; // private static final String FEATURE_CONTEXTS = "contexts"; // private static final String FEATURE_CONTEXT = "context"; // private static final Pattern CONTENT_REGEX = Pattern.compile("\\A\\s*(<[?]xml\\s.*[?]>\\s*)?<" + FEATURE_CONTEXTS + "[\\s>]"); // // public static final String FILENAME = ".contexts.xml"; // // @Override // public APersistentFormat<List<FeatureContext>> getInstance() { // return new FeatureContextFormat(); // } // // @Override // public boolean supportsRead() { // return true; // } // // @Override // public boolean supportsWrite() { // return true; // } // // @Override // public String getId() { // return ID; // } // // @Override // protected void readDocument(Document doc, List<Problem> warnings) throws UnsupportedModelException { // object.clear(); // for (final Element e : getElements(doc.getDocumentElement().getChildNodes())) { // FeatureContext fe = new FeatureContext(e.getAttribute("name"), FeatureColor.getColor(e.getAttribute("highlighter"))); // object.add(fe); // } // // } // // @Override // protected void writeDocument(Document doc) { // final Element root = doc.createElement(FEATURE_CONTEXTS); // // Element e; // for (FeatureContext fe : object) { // e = doc.createElement(FEATURE_CONTEXT); // e.setAttribute("name", fe.name); // e.setAttribute("highlighter", fe.highlighter.getColorName()); // root.appendChild(e); // } // doc.appendChild(root); // } // // @Override // public boolean supportsContent(CharSequence content) { // return supportsRead() && CONTENT_REGEX.matcher(content).find(); // } // // @Override // public String getName() { // return "FeatureContexts"; // } // // }
import java.io.File; import java.io.IOException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResourceDelta; import de.ovgu.featureide.core.builder.ComposerExtensionClass; import de.ovgu.featureide.fm.core.configuration.Configuration; import de.tubs.variantsync.core.managers.persistence.FeatureContextFormat;
package de.tubs.variantsync.core; public class VariantSyncComposer extends ComposerExtensionClass { @Override public void performFullBuild(IFile config) { VariantSyncPlugin.getConfigurationProjectManager().reinitialize(); } @Override public void addCompiler(IProject project, String sourcePath, String configPath, String buildPath) {
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/persistence/FeatureContextFormat.java // public class FeatureContextFormat extends AXMLFormat<List<FeatureContext>> { // // private static final String ID = "FeatureContexts"; // private static final String FEATURE_CONTEXTS = "contexts"; // private static final String FEATURE_CONTEXT = "context"; // private static final Pattern CONTENT_REGEX = Pattern.compile("\\A\\s*(<[?]xml\\s.*[?]>\\s*)?<" + FEATURE_CONTEXTS + "[\\s>]"); // // public static final String FILENAME = ".contexts.xml"; // // @Override // public APersistentFormat<List<FeatureContext>> getInstance() { // return new FeatureContextFormat(); // } // // @Override // public boolean supportsRead() { // return true; // } // // @Override // public boolean supportsWrite() { // return true; // } // // @Override // public String getId() { // return ID; // } // // @Override // protected void readDocument(Document doc, List<Problem> warnings) throws UnsupportedModelException { // object.clear(); // for (final Element e : getElements(doc.getDocumentElement().getChildNodes())) { // FeatureContext fe = new FeatureContext(e.getAttribute("name"), FeatureColor.getColor(e.getAttribute("highlighter"))); // object.add(fe); // } // // } // // @Override // protected void writeDocument(Document doc) { // final Element root = doc.createElement(FEATURE_CONTEXTS); // // Element e; // for (FeatureContext fe : object) { // e = doc.createElement(FEATURE_CONTEXT); // e.setAttribute("name", fe.name); // e.setAttribute("highlighter", fe.highlighter.getColorName()); // root.appendChild(e); // } // doc.appendChild(root); // } // // @Override // public boolean supportsContent(CharSequence content) { // return supportsRead() && CONTENT_REGEX.matcher(content).find(); // } // // @Override // public String getName() { // return "FeatureContexts"; // } // // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/VariantSyncComposer.java import java.io.File; import java.io.IOException; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResourceDelta; import de.ovgu.featureide.core.builder.ComposerExtensionClass; import de.ovgu.featureide.fm.core.configuration.Configuration; import de.tubs.variantsync.core.managers.persistence.FeatureContextFormat; package de.tubs.variantsync.core; public class VariantSyncComposer extends ComposerExtensionClass { @Override public void performFullBuild(IFile config) { VariantSyncPlugin.getConfigurationProjectManager().reinitialize(); } @Override public void addCompiler(IProject project, String sourcePath, String configPath, String buildPath) {
File featureContextFile = new File(project.getFile(FeatureContextFormat.FILENAME).getLocationURI());
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IMarkerHandler.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/SourceFile.java // public class SourceFile { // // private IFile resource; // List<CodeMapping> mappings = new ArrayList<>(); // // public SourceFile(IFile res) { // this.resource = res; // } // // public SourceFile(IFile res, List<CodeMapping> mappings) { // this.resource = res; // this.mappings = mappings; // } // // public IFile getFile() { // return resource; // } // // public void setFile(IFile res) { // this.resource = res; // } // // public List<CodeMapping> getMappings() { // return mappings; // } // // public void addMapping(CodeMapping mapping) { // this.mappings.add(mapping); // } // // public void setMapping(List<CodeMapping> mappings) { // this.mappings = mappings; // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/IVariantSyncMarker.java // public interface IVariantSyncMarker { // // /** // * Returns marker id. // * // * @return markerId // */ // long getMarkerId(); // // /** // * Sets marker id. // * // * @param markerId - id of marker // */ // void setMarkerId(long markerId); // // /** // * Returns offset. // * // * @return offset // */ // int getOffset(); // // /** // * Sets offset. // * // * @param offset // */ // void setOffset(int offset); // // /** // * Returns length. // * // * @return length // */ // int getLength(); // // /** // * Sets length. // * // * @param length // */ // void setLength(int length); // // /** // * Returns feature context. // * // * @return feature context // */ // String getContext(); // // /** // * Sets feature expression. // * // * @param context - feature context // */ // void setContext(String context); // // /** // * Returns whether the complete line is annotated // * // * @return true, if the complete line is annotated // */ // boolean isLine(); // // /** // * Sets whether the complete line is annotated // * // * @param true, if the complete line is annotated // */ // void setLine(boolean isLine); // }
import java.util.List; import org.eclipse.core.resources.IFile; import de.tubs.variantsync.core.managers.data.SourceFile; import de.tubs.variantsync.core.utilities.IVariantSyncMarker;
package de.tubs.variantsync.core.patch.interfaces; public interface IMarkerHandler<T> { List<IVariantSyncMarker> getMarkers(IFile file, int offset, int length); List<IVariantSyncMarker> getMarkersForDelta(IFile file, IDelta<T> delta); List<IVariantSyncMarker> getMarkersForDeltas(IFile file, List<IDelta<T>> deltas);
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/managers/data/SourceFile.java // public class SourceFile { // // private IFile resource; // List<CodeMapping> mappings = new ArrayList<>(); // // public SourceFile(IFile res) { // this.resource = res; // } // // public SourceFile(IFile res, List<CodeMapping> mappings) { // this.resource = res; // this.mappings = mappings; // } // // public IFile getFile() { // return resource; // } // // public void setFile(IFile res) { // this.resource = res; // } // // public List<CodeMapping> getMappings() { // return mappings; // } // // public void addMapping(CodeMapping mapping) { // this.mappings.add(mapping); // } // // public void setMapping(List<CodeMapping> mappings) { // this.mappings = mappings; // } // // } // // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/IVariantSyncMarker.java // public interface IVariantSyncMarker { // // /** // * Returns marker id. // * // * @return markerId // */ // long getMarkerId(); // // /** // * Sets marker id. // * // * @param markerId - id of marker // */ // void setMarkerId(long markerId); // // /** // * Returns offset. // * // * @return offset // */ // int getOffset(); // // /** // * Sets offset. // * // * @param offset // */ // void setOffset(int offset); // // /** // * Returns length. // * // * @return length // */ // int getLength(); // // /** // * Sets length. // * // * @param length // */ // void setLength(int length); // // /** // * Returns feature context. // * // * @return feature context // */ // String getContext(); // // /** // * Sets feature expression. // * // * @param context - feature context // */ // void setContext(String context); // // /** // * Returns whether the complete line is annotated // * // * @return true, if the complete line is annotated // */ // boolean isLine(); // // /** // * Sets whether the complete line is annotated // * // * @param true, if the complete line is annotated // */ // void setLine(boolean isLine); // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/interfaces/IMarkerHandler.java import java.util.List; import org.eclipse.core.resources.IFile; import de.tubs.variantsync.core.managers.data.SourceFile; import de.tubs.variantsync.core.utilities.IVariantSyncMarker; package de.tubs.variantsync.core.patch.interfaces; public interface IMarkerHandler<T> { List<IVariantSyncMarker> getMarkers(IFile file, int offset, int length); List<IVariantSyncMarker> getMarkersForDelta(IFile file, IDelta<T> delta); List<IVariantSyncMarker> getMarkersForDeltas(IFile file, List<IDelta<T>> deltas);
boolean updateMarkerForDelta(SourceFile sourceFile, IDelta<T> delta, List<IVariantSyncMarker> variantSyncMarkers);
tthuem/VariantSync
de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/HistoryStore.java
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/FileHelper.java // public class FileHelper { // // /** // * Returns the latest history of an IFile resource // * // * @param res // * @return // */ // public static IFileState getLatestHistory(IFile res) { // IFileState[] states = null; // try { // states = res.getHistory(null); // } catch (CoreException e) { // LogOperations.logError("File states could not be retrieved.", e); // } // if (states.length > 0) { // return states[0]; // } // return null; // } // // /** // * Returns all lines of an IFile resource as an list of strings // * // * @param res // * @return // */ // public static List<String> getFileLines(IFile res) { // List<String> currentFilelines = new ArrayList<>(); // try { // currentFilelines = readFile(res.getContents(), res.getCharset()); // } catch (CoreException e) { // LogOperations.logError("File could not be accessed.", e); // } // return currentFilelines; // } // // /** // * Returns all lines of an IFile history state resource as an list of strings // * // * @param state // * @return // */ // public static List<String> getFileLines(IFileState state) { // List<String> currentFilelines = new ArrayList<>(); // try { // currentFilelines = readFile(state.getContents(), state.getCharset()); // } catch (CoreException e) { // LogOperations.logError("History can not be accessed.", e); // } // return currentFilelines; // } // // /** // * Overwrites the IFile resource with the given lines // * // * @param res // * @param lines // */ // public static void setFileLines(IFile res, List<String> lines) { // writeFile(res, lines); // } // // /** // * Reads content from file using buffered reader. Adds each line in file to List<String>. // * // * @param in buffered Reader for file // * @param charset // * @return list with file content // */ // private static List<String> readFile(InputStream in, String charset) { // List<String> fileContent = new LinkedList<String>(); // String line = ""; // BufferedReader reader = null; // if (charset == null) charset = (String) "UTF-8"; // try { // reader = new BufferedReader(new InputStreamReader(in, charset)); // while ((line = reader.readLine()) != null) { // fileContent.add(line); // } // } catch (IOException e) { // LogOperations.logError("BufferedReader could not be opened.", e); // } finally { // try { // reader.close(); // } catch (NullPointerException | IOException e) { // LogOperations.logError("BufferedReader could not be closed.", e); // } // } // return fileContent; // } // // /** // * Writes content to a IFile resource using a buffered writer. Each line is one item in lines // * // * @param res // * @param lines // */ // public static void writeFile(IFile res, List<String> lines) { // File file = new File(res.getRawLocationURI()); // if (file.exists()) { // file.delete(); // } // File parentDir = file.getParentFile(); // if (!parentDir.exists()) parentDir.mkdirs(); // PrintWriter out = null; // try { // file.createNewFile(); // out = new PrintWriter(new BufferedWriter(new FileWriter(file))); // for (String line : lines) { // out.println(line); // } // } catch (IOException e) { // LogOperations.logError("File can not be created.", e); // } finally { // if (out != null) { // out.flush(); // out.close(); // } // try { // ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); // } catch (CoreException e) { // LogOperations.logInfo("Refresh could not be made because the workspace is locked up."); // } // } // } // // }
import java.util.List; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import de.tubs.variantsync.core.utilities.FileHelper;
package de.tubs.variantsync.core.patch; public class HistoryStore { public static final String historyFolder = ".history"; public void addHistory(IFile file, List<String> content, long timestamp) { IProject project = file.getProject(); IFile historyFile = project.getFolder(historyFolder).getFolder(file.getProjectRelativePath().toOSString().replace(".", "_").replace("/", "_")) .getFile(timestamp + ".java");
// Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/utilities/FileHelper.java // public class FileHelper { // // /** // * Returns the latest history of an IFile resource // * // * @param res // * @return // */ // public static IFileState getLatestHistory(IFile res) { // IFileState[] states = null; // try { // states = res.getHistory(null); // } catch (CoreException e) { // LogOperations.logError("File states could not be retrieved.", e); // } // if (states.length > 0) { // return states[0]; // } // return null; // } // // /** // * Returns all lines of an IFile resource as an list of strings // * // * @param res // * @return // */ // public static List<String> getFileLines(IFile res) { // List<String> currentFilelines = new ArrayList<>(); // try { // currentFilelines = readFile(res.getContents(), res.getCharset()); // } catch (CoreException e) { // LogOperations.logError("File could not be accessed.", e); // } // return currentFilelines; // } // // /** // * Returns all lines of an IFile history state resource as an list of strings // * // * @param state // * @return // */ // public static List<String> getFileLines(IFileState state) { // List<String> currentFilelines = new ArrayList<>(); // try { // currentFilelines = readFile(state.getContents(), state.getCharset()); // } catch (CoreException e) { // LogOperations.logError("History can not be accessed.", e); // } // return currentFilelines; // } // // /** // * Overwrites the IFile resource with the given lines // * // * @param res // * @param lines // */ // public static void setFileLines(IFile res, List<String> lines) { // writeFile(res, lines); // } // // /** // * Reads content from file using buffered reader. Adds each line in file to List<String>. // * // * @param in buffered Reader for file // * @param charset // * @return list with file content // */ // private static List<String> readFile(InputStream in, String charset) { // List<String> fileContent = new LinkedList<String>(); // String line = ""; // BufferedReader reader = null; // if (charset == null) charset = (String) "UTF-8"; // try { // reader = new BufferedReader(new InputStreamReader(in, charset)); // while ((line = reader.readLine()) != null) { // fileContent.add(line); // } // } catch (IOException e) { // LogOperations.logError("BufferedReader could not be opened.", e); // } finally { // try { // reader.close(); // } catch (NullPointerException | IOException e) { // LogOperations.logError("BufferedReader could not be closed.", e); // } // } // return fileContent; // } // // /** // * Writes content to a IFile resource using a buffered writer. Each line is one item in lines // * // * @param res // * @param lines // */ // public static void writeFile(IFile res, List<String> lines) { // File file = new File(res.getRawLocationURI()); // if (file.exists()) { // file.delete(); // } // File parentDir = file.getParentFile(); // if (!parentDir.exists()) parentDir.mkdirs(); // PrintWriter out = null; // try { // file.createNewFile(); // out = new PrintWriter(new BufferedWriter(new FileWriter(file))); // for (String line : lines) { // out.println(line); // } // } catch (IOException e) { // LogOperations.logError("File can not be created.", e); // } finally { // if (out != null) { // out.flush(); // out.close(); // } // try { // ResourcesPlugin.getWorkspace().getRoot().refreshLocal(IResource.DEPTH_INFINITE, null); // } catch (CoreException e) { // LogOperations.logInfo("Refresh could not be made because the workspace is locked up."); // } // } // } // // } // Path: de.tubs.variantsync.core/src/de/tubs/variantsync/core/patch/HistoryStore.java import java.util.List; import java.util.Set; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IProgressMonitor; import de.tubs.variantsync.core.utilities.FileHelper; package de.tubs.variantsync.core.patch; public class HistoryStore { public static final String historyFolder = ".history"; public void addHistory(IFile file, List<String> content, long timestamp) { IProject project = file.getProject(); IFile historyFile = project.getFolder(historyFolder).getFolder(file.getProjectRelativePath().toOSString().replace(".", "_").replace("/", "_")) .getFile(timestamp + ".java");
FileHelper.setFileLines(historyFile, content);
bogdansolga/java8-training
s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/ConsumersMain.java
// Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java // public class ProductService { // // public void displayAppleTablets() { // final Section tablets = getTabletsSection(); // processAppleTablets(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tablets()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private void processAppleTablets(final Section tablets) { // final List<Product> products = tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // // /* // Q: when to use an inline lambda expression and when to use methods? // A: • use a method: // - if the lambda expression needs to be a statement lambda // and / or // - if it needs to be reused // • usa an inline lambda - if the lambda expression can be written on a single line // */ // // // Single Responsibility Principle / Separation of Concerns // products.stream() // 0 - obtaining a stream from the collection // .filter(appleProducts()) // 1 - filtering stage // .forEach(consumeProduct()); // 2 - processing / consuming stage // } // // private Consumer<Product> consumeProduct() { // return System.out::println; // } // // private Predicate<Product> appleProducts() { // return product -> product.getName().contains("Apple"); // } // // private Predicate<Section> tablets() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // }
import net.safedata.java8.training.consumer.service.ProductService; import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.List; import java.util.function.Consumer;
display.accept("something"); final List<String> list = Arrays.asList("I want a holiday, not just a weekend".split(" ")); // imperative way for (final String item : list) { System.out.println(item); } // functional way list.forEach(System.out::println); list.forEach(item -> System.out.println(item)); // just a matter of taste :) final Consumer<Boolean> booleanConsumer = it -> System.out.println("The boolean value is " + Boolean.valueOf(it)); booleanConsumer.accept(Boolean.TRUE); final Consumer<String> aMoreComplexConsumer = value -> { if (value.isEmpty()) { System.err.println("Cannot process an empty value"); } else { System.out.println("The received value is " + value); } }; final Consumer<String> displayedRecommendationConsumer = value -> { System.out.println("The value is " + value); }; } private static void productConsumers() {
// Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java // public class ProductService { // // public void displayAppleTablets() { // final Section tablets = getTabletsSection(); // processAppleTablets(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tablets()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private void processAppleTablets(final Section tablets) { // final List<Product> products = tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // // /* // Q: when to use an inline lambda expression and when to use methods? // A: • use a method: // - if the lambda expression needs to be a statement lambda // and / or // - if it needs to be reused // • usa an inline lambda - if the lambda expression can be written on a single line // */ // // // Single Responsibility Principle / Separation of Concerns // products.stream() // 0 - obtaining a stream from the collection // .filter(appleProducts()) // 1 - filtering stage // .forEach(consumeProduct()); // 2 - processing / consuming stage // } // // private Consumer<Product> consumeProduct() { // return System.out::println; // } // // private Predicate<Product> appleProducts() { // return product -> product.getName().contains("Apple"); // } // // private Predicate<Section> tablets() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/ConsumersMain.java import net.safedata.java8.training.consumer.service.ProductService; import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; display.accept("something"); final List<String> list = Arrays.asList("I want a holiday, not just a weekend".split(" ")); // imperative way for (final String item : list) { System.out.println(item); } // functional way list.forEach(System.out::println); list.forEach(item -> System.out.println(item)); // just a matter of taste :) final Consumer<Boolean> booleanConsumer = it -> System.out.println("The boolean value is " + Boolean.valueOf(it)); booleanConsumer.accept(Boolean.TRUE); final Consumer<String> aMoreComplexConsumer = value -> { if (value.isEmpty()) { System.err.println("Cannot process an empty value"); } else { System.out.println("The received value is " + value); } }; final Consumer<String> displayedRecommendationConsumer = value -> { System.out.println("The value is " + value); }; } private static void productConsumers() {
final ProductService productService = new ProductService();
bogdansolga/java8-training
s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/ConsumersMain.java
// Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java // public class ProductService { // // public void displayAppleTablets() { // final Section tablets = getTabletsSection(); // processAppleTablets(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tablets()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private void processAppleTablets(final Section tablets) { // final List<Product> products = tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // // /* // Q: when to use an inline lambda expression and when to use methods? // A: • use a method: // - if the lambda expression needs to be a statement lambda // and / or // - if it needs to be reused // • usa an inline lambda - if the lambda expression can be written on a single line // */ // // // Single Responsibility Principle / Separation of Concerns // products.stream() // 0 - obtaining a stream from the collection // .filter(appleProducts()) // 1 - filtering stage // .forEach(consumeProduct()); // 2 - processing / consuming stage // } // // private Consumer<Product> consumeProduct() { // return System.out::println; // } // // private Predicate<Product> appleProducts() { // return product -> product.getName().contains("Apple"); // } // // private Predicate<Section> tablets() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // }
import net.safedata.java8.training.consumer.service.ProductService; import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.List; import java.util.function.Consumer;
} // functional way list.forEach(System.out::println); list.forEach(item -> System.out.println(item)); // just a matter of taste :) final Consumer<Boolean> booleanConsumer = it -> System.out.println("The boolean value is " + Boolean.valueOf(it)); booleanConsumer.accept(Boolean.TRUE); final Consumer<String> aMoreComplexConsumer = value -> { if (value.isEmpty()) { System.err.println("Cannot process an empty value"); } else { System.out.println("The received value is " + value); } }; final Consumer<String> displayedRecommendationConsumer = value -> { System.out.println("The value is " + value); }; } private static void productConsumers() { final ProductService productService = new ProductService(); productService.displayAppleTablets(); // TODO add a method in the ProductService to display all the products with a price bigger than 100 } private static void chainedProductConsumers() {
// Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java // public class ProductService { // // public void displayAppleTablets() { // final Section tablets = getTabletsSection(); // processAppleTablets(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tablets()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private void processAppleTablets(final Section tablets) { // final List<Product> products = tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // // /* // Q: when to use an inline lambda expression and when to use methods? // A: • use a method: // - if the lambda expression needs to be a statement lambda // and / or // - if it needs to be reused // • usa an inline lambda - if the lambda expression can be written on a single line // */ // // // Single Responsibility Principle / Separation of Concerns // products.stream() // 0 - obtaining a stream from the collection // .filter(appleProducts()) // 1 - filtering stage // .forEach(consumeProduct()); // 2 - processing / consuming stage // } // // private Consumer<Product> consumeProduct() { // return System.out::println; // } // // private Predicate<Product> appleProducts() { // return product -> product.getName().contains("Apple"); // } // // private Predicate<Section> tablets() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/ConsumersMain.java import net.safedata.java8.training.consumer.service.ProductService; import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; } // functional way list.forEach(System.out::println); list.forEach(item -> System.out.println(item)); // just a matter of taste :) final Consumer<Boolean> booleanConsumer = it -> System.out.println("The boolean value is " + Boolean.valueOf(it)); booleanConsumer.accept(Boolean.TRUE); final Consumer<String> aMoreComplexConsumer = value -> { if (value.isEmpty()) { System.err.println("Cannot process an empty value"); } else { System.out.println("The received value is " + value); } }; final Consumer<String> displayedRecommendationConsumer = value -> { System.out.println("The value is " + value); }; } private static void productConsumers() { final ProductService productService = new ProductService(); productService.displayAppleTablets(); // TODO add a method in the ProductService to display all the products with a price bigger than 100 } private static void chainedProductConsumers() {
final Product product = new Product(10, "iSomething", 500);
bogdansolga/java8-training
s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // }
import net.safedata.java8.training.model.Product; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Random; import java.util.function.Supplier;
package net.safedata.java8.training.supplier.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { private static final Random RANDOM = new Random(); private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##");
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java import net.safedata.java8.training.model.Product; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Random; import java.util.function.Supplier; package net.safedata.java8.training.supplier.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { private static final Random RANDOM = new Random(); private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##");
public Supplier<Product> generateRandomProduct() {
bogdansolga/java8-training
s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/SuppliersMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java // public class ProductService { // // private static final Random RANDOM = new Random(); // // private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##"); // // public Supplier<Product> generateRandomProduct() { // // advice - try not to do not do this at home (or in your projects) // // (this = mixing lambda expressions and try / catch statements) // return () -> { // try { // return new Product(RANDOM.nextInt(500), "A fancy little random product", // Double.parseDouble(NUMBER_FORMAT.format(RANDOM.nextDouble() * 100))); // } catch (final NumberFormatException e) { // throw new IllegalArgumentException("Invalid number"); // } // }; // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.supplier.service.ProductService; import java.util.Random; import java.util.function.Supplier;
package net.safedata.java8.training.supplier; /** * A few {@link java.util.function.Supplier} usage samples */ public class SuppliersMain { public static void main(String[] args) { simpleSuppliers(); productSuppliers(); sectionSuppliers(); managerSuppliers(); } private static void simpleSuppliers() { final Supplier<Double> doubleSupplier = () -> new Random(2525325).nextDouble(); System.out.println(doubleSupplier.get()); final Supplier<String> holidaySupplier = () -> "I want a holiday, not just a weekend :)"; System.out.println(holidaySupplier.get()); final Supplier<RuntimeException> runtimeExceptionSupplier = () -> new IllegalArgumentException("Nope"); System.err.println(runtimeExceptionSupplier.get().getMessage()); // TODO try other simple Suppliers - String, Boolean, ... } private static void productSuppliers() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java // public class ProductService { // // private static final Random RANDOM = new Random(); // // private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##"); // // public Supplier<Product> generateRandomProduct() { // // advice - try not to do not do this at home (or in your projects) // // (this = mixing lambda expressions and try / catch statements) // return () -> { // try { // return new Product(RANDOM.nextInt(500), "A fancy little random product", // Double.parseDouble(NUMBER_FORMAT.format(RANDOM.nextDouble() * 100))); // } catch (final NumberFormatException e) { // throw new IllegalArgumentException("Invalid number"); // } // }; // } // } // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/SuppliersMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.supplier.service.ProductService; import java.util.Random; import java.util.function.Supplier; package net.safedata.java8.training.supplier; /** * A few {@link java.util.function.Supplier} usage samples */ public class SuppliersMain { public static void main(String[] args) { simpleSuppliers(); productSuppliers(); sectionSuppliers(); managerSuppliers(); } private static void simpleSuppliers() { final Supplier<Double> doubleSupplier = () -> new Random(2525325).nextDouble(); System.out.println(doubleSupplier.get()); final Supplier<String> holidaySupplier = () -> "I want a holiday, not just a weekend :)"; System.out.println(holidaySupplier.get()); final Supplier<RuntimeException> runtimeExceptionSupplier = () -> new IllegalArgumentException("Nope"); System.err.println(runtimeExceptionSupplier.get().getMessage()); // TODO try other simple Suppliers - String, Boolean, ... } private static void productSuppliers() {
final ProductService productService = new ProductService();
bogdansolga/java8-training
s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/SuppliersMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java // public class ProductService { // // private static final Random RANDOM = new Random(); // // private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##"); // // public Supplier<Product> generateRandomProduct() { // // advice - try not to do not do this at home (or in your projects) // // (this = mixing lambda expressions and try / catch statements) // return () -> { // try { // return new Product(RANDOM.nextInt(500), "A fancy little random product", // Double.parseDouble(NUMBER_FORMAT.format(RANDOM.nextDouble() * 100))); // } catch (final NumberFormatException e) { // throw new IllegalArgumentException("Invalid number"); // } // }; // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.supplier.service.ProductService; import java.util.Random; import java.util.function.Supplier;
package net.safedata.java8.training.supplier; /** * A few {@link java.util.function.Supplier} usage samples */ public class SuppliersMain { public static void main(String[] args) { simpleSuppliers(); productSuppliers(); sectionSuppliers(); managerSuppliers(); } private static void simpleSuppliers() { final Supplier<Double> doubleSupplier = () -> new Random(2525325).nextDouble(); System.out.println(doubleSupplier.get()); final Supplier<String> holidaySupplier = () -> "I want a holiday, not just a weekend :)"; System.out.println(holidaySupplier.get()); final Supplier<RuntimeException> runtimeExceptionSupplier = () -> new IllegalArgumentException("Nope"); System.err.println(runtimeExceptionSupplier.get().getMessage()); // TODO try other simple Suppliers - String, Boolean, ... } private static void productSuppliers() { final ProductService productService = new ProductService();
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/service/ProductService.java // public class ProductService { // // private static final Random RANDOM = new Random(); // // private static final NumberFormat NUMBER_FORMAT = new DecimalFormat("##.##"); // // public Supplier<Product> generateRandomProduct() { // // advice - try not to do not do this at home (or in your projects) // // (this = mixing lambda expressions and try / catch statements) // return () -> { // try { // return new Product(RANDOM.nextInt(500), "A fancy little random product", // Double.parseDouble(NUMBER_FORMAT.format(RANDOM.nextDouble() * 100))); // } catch (final NumberFormatException e) { // throw new IllegalArgumentException("Invalid number"); // } // }; // } // } // Path: s01/s01e05-suppliers/src/main/java/net/safedata/java8/training/supplier/SuppliersMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.supplier.service.ProductService; import java.util.Random; import java.util.function.Supplier; package net.safedata.java8.training.supplier; /** * A few {@link java.util.function.Supplier} usage samples */ public class SuppliersMain { public static void main(String[] args) { simpleSuppliers(); productSuppliers(); sectionSuppliers(); managerSuppliers(); } private static void simpleSuppliers() { final Supplier<Double> doubleSupplier = () -> new Random(2525325).nextDouble(); System.out.println(doubleSupplier.get()); final Supplier<String> holidaySupplier = () -> "I want a holiday, not just a weekend :)"; System.out.println(holidaySupplier.get()); final Supplier<RuntimeException> runtimeExceptionSupplier = () -> new IllegalArgumentException("Nope"); System.err.println(runtimeExceptionSupplier.get().getMessage()); // TODO try other simple Suppliers - String, Boolean, ... } private static void productSuppliers() { final ProductService productService = new ProductService();
final Product product = productService.generateRandomProduct().get();
bogdansolga/java8-training
s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // }
import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream;
package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle();
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // Path: s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream; package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle();
final Store store = StoreSetup.getDefaultStore();
bogdansolga/java8-training
s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // }
import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream;
package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle();
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // Path: s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream; package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle();
final Store store = StoreSetup.getDefaultStore();
bogdansolga/java8-training
s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // }
import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream;
package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle(); final Store store = StoreSetup.getDefaultStore(); return store.getStoreSections() .stream()
// Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Store.java // public class Store extends AbstractEntity { // // private final int id; // private final String name; // private final String location; // private final Set<Section> storeSections; // private final Set<Manager> storeManagers; // // public Store(final int id, final String name, final String location, // final Set<Section> storeSections, final Set<Manager> storeManagers) { // this.id = id; // this.name = name; // this.location = location; // this.storeSections = storeSections; // this.storeManagers = storeManagers; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public String getLocation() { // return location; // } // // public Set<Manager> getStoreManagers() { // return storeManagers; // } // // public Set<Section> getStoreSections() { // return storeSections; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Store)) return false; // Store store = (Store) o; // return id == store.id && // Objects.equals(name, store.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // Path: s03/s03e03-completable-future/src/main/java/net/safedata/java8/training/completable/future/ProductProcessor.java import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.model.Store; import org.jooq.lambda.Unchecked; import java.util.ArrayList; import java.util.Random; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.IntStream; package net.safedata.java8.training.completable.future; class ProductProcessor { private static final Random RANDOM = new Random(); private static final int MAX_SLEEP_TIME = 2000; CompletableFuture<Long> getProductsStock(final String productName) { return CompletableFuture.supplyAsync(() -> { displayStageAndThreadName("Getting the product stock for '" + productName + "'"); sleepALittle(); final Store store = StoreSetup.getDefaultStore(); return store.getStoreSections() .stream()
.map(Section::getProducts)
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() {
final Section tabletsSection = getTabletsSection();
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection();
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection();
final List<Product> tablets = getProductsOrThrow(tabletsSection);
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection(); final List<Product> tablets = getProductsOrThrow(tabletsSection); return getSamsungTabletsDescriptions(tablets); } private Section getTabletsSection() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection(); final List<Product> tablets = getProductsOrThrow(tabletsSection); return getSamsungTabletsDescriptions(tablets); } private Section getTabletsSection() {
return StoreSetup.getDefaultStore()
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection(); final List<Product> tablets = getProductsOrThrow(tabletsSection); return getSamsungTabletsDescriptions(tablets); } private Section getTabletsSection() { return StoreSetup.getDefaultStore() .getStoreSections() .stream()
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.function.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public Set<String> getSamsungTabletDescriptions() { final Section tabletsSection = getTabletsSection(); final List<Product> tablets = getProductsOrThrow(tabletsSection); return getSamsungTabletsDescriptions(tablets); } private Section getTabletsSection() { return StoreSetup.getDefaultStore() .getStoreSections() .stream()
.filter(section -> section.getName().equals(StoreSection.Tablets))
bogdansolga/java8-training
s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.predicate.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public List<Product> getNexusTablets() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.predicate.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public List<Product> getNexusTablets() {
final Section tablets = getTablets();
bogdansolga/java8-training
s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors;
package net.safedata.java8.training.predicate.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public List<Product> getNexusTablets() { final Section tablets = getTablets(); final List<Product> products = getProductsOrThrow(tablets); return getNexusTablets(products); } private Section getTablets() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; package net.safedata.java8.training.predicate.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public List<Product> getNexusTablets() { final Section tablets = getTablets(); final List<Product> products = getProductsOrThrow(tablets); return getNexusTablets(products); } private Section getTablets() {
return StoreSetup.getDefaultStore()
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // }
import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*;
package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) {
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*; package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) {
List<Student> students = setUp();
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // }
import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*;
package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? //With postal code students.stream() .filter(student -> student.getName().equals("Mihai")) .findAny() .flatMap(Student::getTemporaryAddress)
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*; package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? //With postal code students.stream() .filter(student -> student.getName().equals("Mihai")) .findAny() .flatMap(Student::getTemporaryAddress)
.flatMap(Address::getPostalCode)
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // }
import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*;
package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? //With postal code students.stream() .filter(student -> student.getName().equals("Mihai")) .findAny() .flatMap(Student::getTemporaryAddress) .flatMap(Address::getPostalCode) .filter(postalCode -> !postalCode.getPrefix().equals("RO")) .ifPresent(code -> System.out.println("The postal code is : " +code.getPrefix() + "" + code.getNumber())); //Without postal code students.stream() .filter(student -> student.getName().equals("Mihaela")) .findAny() .flatMap(Student::getTemporaryAddress) .flatMap(Address::getPostalCode) .filter(postalCode -> !postalCode.getPrefix().equals("RO")) .ifPresent(code -> System.out.println("The postal code is : " +code.getPrefix() + "" + code.getNumber())); } private static List<Student> setUp() {
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Address.java // public class Address { // // private int nr; // private String street; // private String country; // private String city; // private Optional<PostalCode> postalCode = Optional.empty(); // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public Optional<PostalCode> getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = Optional.of(postalCode); // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Optional<Address> temporaryAddress = Optional.empty(); // // public Student(String name, Address address) { // this.address = address; // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Optional<Address> getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = Optional.ofNullable(temporaryAddress); // } // // public String getName() { // return name; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/with/flatmap/FlatMapExample.java import net.safedata.java8.training.optional.with.flatmap.model.Address; import net.safedata.java8.training.optional.with.flatmap.model.Student; import net.safedata.java8.training.optional.with.flatmap.model.PostalCode; import java.util.*; package net.safedata.java8.training.optional.with.flatmap; public class FlatMapExample { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? //With postal code students.stream() .filter(student -> student.getName().equals("Mihai")) .findAny() .flatMap(Student::getTemporaryAddress) .flatMap(Address::getPostalCode) .filter(postalCode -> !postalCode.getPrefix().equals("RO")) .ifPresent(code -> System.out.println("The postal code is : " +code.getPrefix() + "" + code.getNumber())); //Without postal code students.stream() .filter(student -> student.getName().equals("Mihaela")) .findAny() .flatMap(Student::getTemporaryAddress) .flatMap(Address::getPostalCode) .filter(postalCode -> !postalCode.getPrefix().equals("RO")) .ifPresent(code -> System.out.println("The postal code is : " +code.getPrefix() + "" + code.getNumber())); } private static List<Student> setUp() {
PostalCode roCode = new PostalCode(10011, "RO");
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/FunctionsMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java // public class ProductService { // // public Set<String> getSamsungTabletDescriptions() { // final Section tabletsSection = getTabletsSection(); // // final List<Product> tablets = getProductsOrThrow(tabletsSection); // // return getSamsungTabletsDescriptions(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(section -> section.getName().equals(StoreSection.Tablets)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private Set<String> getSamsungTabletsDescriptions(final List<Product> tablets) { // return tablets.stream() // .filter(samsungProductsFilter()) // .map(convertProductToString()) // .peek(traceItem()) // .collect(Collectors.toSet()); // } // // private List<Product> getProductsOrThrow(Section tabletsSection) { // return tabletsSection.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // } // // private Consumer<String> traceItem() { // return System.out::println; // } // // private Predicate<Product> samsungProductsFilter() { // return product -> product.getName().contains("Samsung"); // } // // private Function<Product, String> convertProductToString() { // return product -> "The product is: " + product.toString(); // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.function.service.ProductService; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function;
Function<String, Integer> third = value -> { System.out.println("third - " + value.length() * 10); return value.length() * 10; }; System.out.println(first.andThen(second) .andThen(third) .apply("something")); System.out.println(); // first applies the {@code before} function to its input, // and then applies this function to the result System.out.println(first.compose(second) .compose(third) .apply("f(g(h(x)))")); // any text can go in here } private static void mapFunctions() { final Map<Integer, String> weekDays = new HashMap<>(); weekDays.put(1, "Monday"); weekDays.put(2, "Tuesday"); // new methods were added to the Map interface weekDays.computeIfAbsent(3, value -> "The 3rd day"); // aka Wednesday weekDays.forEach((key, value) -> System.out.println(key + " -> " + value)); } private static void productFunctions() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java // public class ProductService { // // public Set<String> getSamsungTabletDescriptions() { // final Section tabletsSection = getTabletsSection(); // // final List<Product> tablets = getProductsOrThrow(tabletsSection); // // return getSamsungTabletsDescriptions(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(section -> section.getName().equals(StoreSection.Tablets)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private Set<String> getSamsungTabletsDescriptions(final List<Product> tablets) { // return tablets.stream() // .filter(samsungProductsFilter()) // .map(convertProductToString()) // .peek(traceItem()) // .collect(Collectors.toSet()); // } // // private List<Product> getProductsOrThrow(Section tabletsSection) { // return tabletsSection.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // } // // private Consumer<String> traceItem() { // return System.out::println; // } // // private Predicate<Product> samsungProductsFilter() { // return product -> product.getName().contains("Samsung"); // } // // private Function<Product, String> convertProductToString() { // return product -> "The product is: " + product.toString(); // } // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/FunctionsMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.function.service.ProductService; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; Function<String, Integer> third = value -> { System.out.println("third - " + value.length() * 10); return value.length() * 10; }; System.out.println(first.andThen(second) .andThen(third) .apply("something")); System.out.println(); // first applies the {@code before} function to its input, // and then applies this function to the result System.out.println(first.compose(second) .compose(third) .apply("f(g(h(x)))")); // any text can go in here } private static void mapFunctions() { final Map<Integer, String> weekDays = new HashMap<>(); weekDays.put(1, "Monday"); weekDays.put(2, "Tuesday"); // new methods were added to the Map interface weekDays.computeIfAbsent(3, value -> "The 3rd day"); // aka Wednesday weekDays.forEach((key, value) -> System.out.println(key + " -> " + value)); } private static void productFunctions() {
final Product aFancyAppleProduct = new Product(10, "iSomething", 500);
bogdansolga/java8-training
s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/FunctionsMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java // public class ProductService { // // public Set<String> getSamsungTabletDescriptions() { // final Section tabletsSection = getTabletsSection(); // // final List<Product> tablets = getProductsOrThrow(tabletsSection); // // return getSamsungTabletsDescriptions(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(section -> section.getName().equals(StoreSection.Tablets)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private Set<String> getSamsungTabletsDescriptions(final List<Product> tablets) { // return tablets.stream() // .filter(samsungProductsFilter()) // .map(convertProductToString()) // .peek(traceItem()) // .collect(Collectors.toSet()); // } // // private List<Product> getProductsOrThrow(Section tabletsSection) { // return tabletsSection.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // } // // private Consumer<String> traceItem() { // return System.out::println; // } // // private Predicate<Product> samsungProductsFilter() { // return product -> product.getName().contains("Samsung"); // } // // private Function<Product, String> convertProductToString() { // return product -> "The product is: " + product.toString(); // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.function.service.ProductService; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function;
System.out.println(first.andThen(second) .andThen(third) .apply("something")); System.out.println(); // first applies the {@code before} function to its input, // and then applies this function to the result System.out.println(first.compose(second) .compose(third) .apply("f(g(h(x)))")); // any text can go in here } private static void mapFunctions() { final Map<Integer, String> weekDays = new HashMap<>(); weekDays.put(1, "Monday"); weekDays.put(2, "Tuesday"); // new methods were added to the Map interface weekDays.computeIfAbsent(3, value -> "The 3rd day"); // aka Wednesday weekDays.forEach((key, value) -> System.out.println(key + " -> " + value)); } private static void productFunctions() { final Product aFancyAppleProduct = new Product(10, "iSomething", 500); final Function<Product, String> productPrinter = it -> it.toString(); //Product::toString productPrinter.apply(aFancyAppleProduct);
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/service/ProductService.java // public class ProductService { // // public Set<String> getSamsungTabletDescriptions() { // final Section tabletsSection = getTabletsSection(); // // final List<Product> tablets = getProductsOrThrow(tabletsSection); // // return getSamsungTabletsDescriptions(tablets); // } // // private Section getTabletsSection() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(section -> section.getName().equals(StoreSection.Tablets)) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private Set<String> getSamsungTabletsDescriptions(final List<Product> tablets) { // return tablets.stream() // .filter(samsungProductsFilter()) // .map(convertProductToString()) // .peek(traceItem()) // .collect(Collectors.toSet()); // } // // private List<Product> getProductsOrThrow(Section tabletsSection) { // return tabletsSection.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no products")); // } // // private Consumer<String> traceItem() { // return System.out::println; // } // // private Predicate<Product> samsungProductsFilter() { // return product -> product.getName().contains("Samsung"); // } // // private Function<Product, String> convertProductToString() { // return product -> "The product is: " + product.toString(); // } // } // Path: s01/s01e04-functions/src/main/java/net/safedata/java8/training/function/FunctionsMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.function.service.ProductService; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; System.out.println(first.andThen(second) .andThen(third) .apply("something")); System.out.println(); // first applies the {@code before} function to its input, // and then applies this function to the result System.out.println(first.compose(second) .compose(third) .apply("f(g(h(x)))")); // any text can go in here } private static void mapFunctions() { final Map<Integer, String> weekDays = new HashMap<>(); weekDays.put(1, "Monday"); weekDays.put(2, "Tuesday"); // new methods were added to the Map interface weekDays.computeIfAbsent(3, value -> "The 3rd day"); // aka Wednesday weekDays.forEach((key, value) -> System.out.println(key + " -> " + value)); } private static void productFunctions() { final Product aFancyAppleProduct = new Product(10, "iSomething", 500); final Function<Product, String> productPrinter = it -> it.toString(); //Product::toString productPrinter.apply(aFancyAppleProduct);
final ProductService productService = new ProductService();
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // }
import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) {
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) {
List<Student> students = setUp();
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // }
import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? for (Student student : students) { if (student.getTemporaryAddress() != null) {
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? for (Student student : students) { if (student.getTemporaryAddress() != null) {
Address temporaryAddress = student.getTemporaryAddress();
bogdansolga/java8-training
s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // }
import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List;
package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? for (Student student : students) { if (student.getTemporaryAddress() != null) { Address temporaryAddress = student.getTemporaryAddress(); if (temporaryAddress.getPostalCode() != null) {
// Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Address.java // public class Address { // private int nr; // private String street; // private String country; // private String city; // private PostalCode postalCode; // // public Address(int nr, String street, String country, String city) { // this.nr = nr; // this.street = street; // this.country = country; // this.city = city; // } // // public int getNr() { // return nr; // } // // public void setNr(int nr) { // this.nr = nr; // } // // public String getStreet() { // return street; // } // // public void setStreet(String street) { // this.street = street; // } // // public String getCountry() { // return country; // } // // public void setCountry(String country) { // this.country = country; // } // // public String getCity() { // return city; // } // // public void setCity(String city) { // this.city = city; // } // // public PostalCode getPostalCode() { // return postalCode; // } // // public void setPostalCode(PostalCode postalCode) { // this.postalCode = postalCode; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/PostalCode.java // public class PostalCode { // // private int number; // private String prefix; // // public PostalCode(int number, String prefix) { // this.number = number; // this.prefix = prefix; // } // // public int getNumber() { // return number; // } // // public void setNumber(int number) { // this.number = number; // } // // public String getPrefix() { // return prefix; // } // // public void setPrefix(String prefix) { // this.prefix = prefix; // } // } // // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/model/Student.java // public class Student { // // private String name; // private Address address; // private Address temporaryAddress; // // public Student(String name, Address address) { // this.name = name; // this.address = address; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Address getAddress() { // return address; // } // // public void setAddress(Address address) { // this.address = address; // } // // public Address getTemporaryAddress() { // return temporaryAddress; // } // // public void setTemporaryAddress(Address temporaryAddress) { // this.temporaryAddress = temporaryAddress; // } // } // Path: s02/s02e01-optional/src/main/java/net/safedata/java8/training/optional/without/flatmap/OldSchoolWay.java import net.safedata.java8.training.optional.without.flatmap.model.Address; import net.safedata.java8.training.optional.without.flatmap.model.PostalCode; import net.safedata.java8.training.optional.without.flatmap.model.Student; import java.util.ArrayList; import java.util.Arrays; import java.util.List; package net.safedata.java8.training.optional.without.flatmap; public class OldSchoolWay { public static void main(String[] args) { List<Student> students = setUp(); //Do I have any student with a temporary address abroad ? for (Student student : students) { if (student.getTemporaryAddress() != null) { Address temporaryAddress = student.getTemporaryAddress(); if (temporaryAddress.getPostalCode() != null) {
PostalCode code = temporaryAddress.getPostalCode();
bogdansolga/java8-training
s02/s02e02-streams/src/main/java/net/safedata/java8/training/streams/SortingSamples.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // }
import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
package net.safedata.java8.training.streams; public class SortingSamples { public static void main(String[] args) { final List<String> strings = Arrays.asList("some", "random", null, "strings", "and", null, "values"); final List<String> notNullValues = strings.stream() .filter(Objects::nonNull) .sorted() .collect(Collectors.toList()); System.out.println(notNullValues);
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // Path: s02/s02e02-streams/src/main/java/net/safedata/java8/training/streams/SortingSamples.java import net.safedata.java8.training.model.Product; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; package net.safedata.java8.training.streams; public class SortingSamples { public static void main(String[] args) { final List<String> strings = Arrays.asList("some", "random", null, "strings", "and", null, "values"); final List<String> notNullValues = strings.stream() .filter(Objects::nonNull) .sorted() .collect(Collectors.toList()); System.out.println(notNullValues);
final List<Product> products = Arrays.asList(
bogdansolga/java8-training
s03/s03e02-jool-usage/src/main/java/net/safedata/java8/training/jool/TupleMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // }
import net.safedata.java8.training.model.Product; import org.jooq.lambda.tuple.Tuple2; import org.jooq.lambda.tuple.Tuple3;
package net.safedata.java8.training.jool; /** * A short sample of using {@link org.jooq.lambda.tuple.Tuple}s */ public class TupleMain { public static void main(String[] args) { // recommended usage - *only* as lambda expression parameters Tuple2<String, Integer> tuple = new Tuple2<>("value", 6); System.out.println(tuple.v2());
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // Path: s03/s03e02-jool-usage/src/main/java/net/safedata/java8/training/jool/TupleMain.java import net.safedata.java8.training.model.Product; import org.jooq.lambda.tuple.Tuple2; import org.jooq.lambda.tuple.Tuple3; package net.safedata.java8.training.jool; /** * A short sample of using {@link org.jooq.lambda.tuple.Tuple}s */ public class TupleMain { public static void main(String[] args) { // recommended usage - *only* as lambda expression parameters Tuple2<String, Integer> tuple = new Tuple2<>("value", 6); System.out.println(tuple.v2());
Tuple3<Integer, Product, String> tuple3 =
bogdansolga/java8-training
s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate;
package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() {
final Section tablets = getTabletsSection();
bogdansolga/java8-training
s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate;
package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() { final Section tablets = getTabletsSection(); processAppleTablets(tablets); } private Section getTabletsSection() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() { final Section tablets = getTabletsSection(); processAppleTablets(tablets); } private Section getTabletsSection() {
return StoreSetup.getDefaultStore()
bogdansolga/java8-training
s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate;
package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() { final Section tablets = getTabletsSection(); processAppleTablets(tablets); } private Section getTabletsSection() { return StoreSetup.getDefaultStore() .getStoreSections() .stream() .filter(tablets()) .findFirst() .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); } private void processAppleTablets(final Section tablets) {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/Section.java // public class Section extends AbstractEntity { // // private final int id; // private final StoreSection name; // private final List<Product> products; // // public Section(final int id, final StoreSection name, final List<Product> products) { // this.id = id; // this.name = name; // this.products = products; // } // // public int getId() { // return id; // } // // public StoreSection getName() { // return name; // } // // public Optional<List<Product>> getProducts() { // return Optional.ofNullable(products); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Section)) return false; // Section that = (Section) o; // return id == that.id && // Objects.equals(name, that.name); // } // // @Override // public int hashCode() { // return Objects.hash(id, name); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/bootstrap/StoreSetup.java // public final class StoreSetup { // // private static Store defaultStore; // // static { // final Section tabletsSection = new Section(1, StoreSection.Tablets, buildDefaultTablets()); // final Section monitorsSection = new Section(2, StoreSection.Monitors, buildDefaultMonitors()); // final Section laptopsSection = new Section(3, StoreSection.Laptops, buildDefaultLaptops()); // // final Manager john = new Manager(1, "John Doe"); // final Manager jane = new Manager(2, "Jane Charming"); // // defaultStore = new Store(1, "Goodies", "Over there", // new HashSet<>(Arrays.asList(tabletsSection, monitorsSection, laptopsSection)), // new HashSet<>(Arrays.asList(john, jane))); // } // // public static Store getDefaultStore() { // return defaultStore; // } // // private StoreSetup() {} // // private static List<Product> buildDefaultTablets() { // return Arrays.asList( // new Product(1, "Google Nexus 7 2013", 200, new Discount(50, Discount.Type.Value)), // new Product(2, "Apple iPad Pro 9.7", 300, new Discount(10, Discount.Type.Percent)), // new Product(3, "Samsung Galaxy Tab S2", 350), // new Product(4, "Microsoft Surface Pro 4", 400) // ); // } // // private static List<Product> buildDefaultMonitors() { // return Arrays.asList( // new Product(5, "Samsung CF791", 500), // new Product(6, "LG 32UD99", 550), // new Product(7, "Samsung CH711", 600) // ); // } // // private static List<Product> buildDefaultLaptops() { // return Arrays.asList( // new Product(10, "Lenovo X11", 1500), // new Product(11, "Apple MacBook Pro", 2000) // ); // } // } // // Path: domain-model/src/main/java/net/safedata/java8/training/model/StoreSection.java // public enum StoreSection { // Tablets, // Monitors, // Laptops // } // Path: s01/s01e03-consumers/src/main/java/net/safedata/java8/training/consumer/service/ProductService.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.model.Section; import net.safedata.java8.training.bootstrap.StoreSetup; import net.safedata.java8.training.model.StoreSection; import java.util.List; import java.util.function.Consumer; import java.util.function.Predicate; package net.safedata.java8.training.consumer.service; /** * A simple service for managing {@link Product} entities * * @author bogdan.solga */ public class ProductService { public void displayAppleTablets() { final Section tablets = getTabletsSection(); processAppleTablets(tablets); } private Section getTabletsSection() { return StoreSetup.getDefaultStore() .getStoreSections() .stream() .filter(tablets()) .findFirst() .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); } private void processAppleTablets(final Section tablets) {
final List<Product> products = tablets.getProducts()
bogdansolga/java8-training
s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/PredicatesMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java // public class ProductService { // // public List<Product> getNexusTablets() { // final Section tablets = getTablets(); // // final List<Product> products = getProductsOrThrow(tablets); // // return getNexusTablets(products); // } // // private Section getTablets() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tabletsSection()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private List<Product> getProductsOrThrow(final Section tablets) { // return tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no available tablets")); // } // // private List<Product> getNexusTablets(final List<Product> products) { // return products.stream() // .filter(product -> product.getName().toLowerCase().contains("nexus")) // .collect(Collectors.toList()); // } // // private Predicate<Section> tabletsSection() { // return section -> section.getName().equals(StoreSection.Tablets); // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.predicate.service.ProductService; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream;
} }; final Predicate<Double> singleStatementMethodPredicate = predicateAsSingleStatementMethod(); singleStatementMethodPredicate.test(515d); final Predicate<Double> multipleStatementsMethodPredicate = predicateAsMultipleStatementMethod(); multipleStatementsMethodPredicate.test(441d); // TODO try other simple predicates - Integer, String, ... } private static void removeCollectionItems() { // removing the elements of a collection - imperative and functional // imperative way final List<String> strings = Arrays.asList("I want a holiday".split(" ")); final Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String value = iterator.next(); if (value.length() < 2) { iterator.remove(); } } // functional way strings.removeIf(value -> value.length() < 2); } private static void productPredicates() {
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java // public class ProductService { // // public List<Product> getNexusTablets() { // final Section tablets = getTablets(); // // final List<Product> products = getProductsOrThrow(tablets); // // return getNexusTablets(products); // } // // private Section getTablets() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tabletsSection()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private List<Product> getProductsOrThrow(final Section tablets) { // return tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no available tablets")); // } // // private List<Product> getNexusTablets(final List<Product> products) { // return products.stream() // .filter(product -> product.getName().toLowerCase().contains("nexus")) // .collect(Collectors.toList()); // } // // private Predicate<Section> tabletsSection() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/PredicatesMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.predicate.service.ProductService; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream; } }; final Predicate<Double> singleStatementMethodPredicate = predicateAsSingleStatementMethod(); singleStatementMethodPredicate.test(515d); final Predicate<Double> multipleStatementsMethodPredicate = predicateAsMultipleStatementMethod(); multipleStatementsMethodPredicate.test(441d); // TODO try other simple predicates - Integer, String, ... } private static void removeCollectionItems() { // removing the elements of a collection - imperative and functional // imperative way final List<String> strings = Arrays.asList("I want a holiday".split(" ")); final Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String value = iterator.next(); if (value.length() < 2) { iterator.remove(); } } // functional way strings.removeIf(value -> value.length() < 2); } private static void productPredicates() {
final Product product = new Product(10, "iSomething", 500);
bogdansolga/java8-training
s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/PredicatesMain.java
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java // public class ProductService { // // public List<Product> getNexusTablets() { // final Section tablets = getTablets(); // // final List<Product> products = getProductsOrThrow(tablets); // // return getNexusTablets(products); // } // // private Section getTablets() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tabletsSection()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private List<Product> getProductsOrThrow(final Section tablets) { // return tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no available tablets")); // } // // private List<Product> getNexusTablets(final List<Product> products) { // return products.stream() // .filter(product -> product.getName().toLowerCase().contains("nexus")) // .collect(Collectors.toList()); // } // // private Predicate<Section> tabletsSection() { // return section -> section.getName().equals(StoreSection.Tablets); // } // }
import net.safedata.java8.training.model.Product; import net.safedata.java8.training.predicate.service.ProductService; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream;
multipleStatementsMethodPredicate.test(441d); // TODO try other simple predicates - Integer, String, ... } private static void removeCollectionItems() { // removing the elements of a collection - imperative and functional // imperative way final List<String> strings = Arrays.asList("I want a holiday".split(" ")); final Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String value = iterator.next(); if (value.length() < 2) { iterator.remove(); } } // functional way strings.removeIf(value -> value.length() < 2); } private static void productPredicates() { final Product product = new Product(10, "iSomething", 500); final Predicate<Product> hasAppleBranding = it -> it.getName().startsWith("i"); System.out.println(hasAppleBranding.test(product)); Predicate<Product> isCheap = it -> it.getPrice() < 100; System.out.println(isCheap.test(product));
// Path: domain-model/src/main/java/net/safedata/java8/training/model/Product.java // public class Product extends AbstractEntity { // // private final int id; // private final String name; // private final double price; // private final Discount discount; // private final List<String> tags; // // public Product(final int id, final String name, final double price, final Discount discount, // final List<String> tags) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = tags; // } // // public Product(final int id, final String name, final double price, final Discount discount) { // this.id = id; // this.name = name; // this.price = price; // this.discount = discount; // this.tags = null; // } // // public Product(final int id, final String name, final double price) { // this.id = id; // this.name = name; // this.price = price; // this.discount = null; // this.tags = null; // } // // public int getId() { // return id; // } // // public String getName() { // return name; // } // // public double getPrice() { // return price; // } // // public Optional<Discount> getDiscount() { // return Optional.ofNullable(discount); // } // // public Optional<List<String>> getTags() { // return Optional.ofNullable(tags); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (!(o instanceof Product)) return false; // Product product = (Product) o; // return id == product.id && // Objects.equals(name, product.name) && // Objects.equals(price, product.price); // } // // @Override // public int hashCode() { // return Objects.hash(id, name, price); // } // // @Override // public String toString() { // return id + ", " + name + ": " + price; // } // } // // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/service/ProductService.java // public class ProductService { // // public List<Product> getNexusTablets() { // final Section tablets = getTablets(); // // final List<Product> products = getProductsOrThrow(tablets); // // return getNexusTablets(products); // } // // private Section getTablets() { // return StoreSetup.getDefaultStore() // .getStoreSections() // .stream() // .filter(tabletsSection()) // .findFirst() // .orElseThrow(() -> new IllegalArgumentException("There's no section named 'Tablets'")); // } // // private List<Product> getProductsOrThrow(final Section tablets) { // return tablets.getProducts() // .orElseThrow(() -> new IllegalArgumentException("There are no available tablets")); // } // // private List<Product> getNexusTablets(final List<Product> products) { // return products.stream() // .filter(product -> product.getName().toLowerCase().contains("nexus")) // .collect(Collectors.toList()); // } // // private Predicate<Section> tabletsSection() { // return section -> section.getName().equals(StoreSection.Tablets); // } // } // Path: s01/s01e02-predicates/src/main/java/net/safedata/java8/training/predicate/PredicatesMain.java import net.safedata.java8.training.model.Product; import net.safedata.java8.training.predicate.service.ProductService; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Stream; multipleStatementsMethodPredicate.test(441d); // TODO try other simple predicates - Integer, String, ... } private static void removeCollectionItems() { // removing the elements of a collection - imperative and functional // imperative way final List<String> strings = Arrays.asList("I want a holiday".split(" ")); final Iterator<String> iterator = strings.iterator(); while (iterator.hasNext()) { String value = iterator.next(); if (value.length() < 2) { iterator.remove(); } } // functional way strings.removeIf(value -> value.length() < 2); } private static void productPredicates() { final Product product = new Product(10, "iSomething", 500); final Predicate<Product> hasAppleBranding = it -> it.getName().startsWith("i"); System.out.println(hasAppleBranding.test(product)); Predicate<Product> isCheap = it -> it.getPrice() < 100; System.out.println(isCheap.test(product));
final ProductService productService = new ProductService();
ivannp/tradelib
src/test/java/net/tradelib/functors/StdDevTest.java
// Path: src/main/java/net/tradelib/functors/StdDev.java // public class StdDev { // private EvictingQueue<Double> eq; // private double mean; // private double var; // private int count; // private int n; // private double dn; // N as a double // // public StdDev(int n) { // this.mean = 0.0; // this.var = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // this.eq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // double oldMean = mean; // mean += (value - eq.peek()) / dn; // var += (value - mean + eq.peek() - oldMean)*(value - eq.peek()) / (dn - 1.0); // } else if(count == n) { // double newMean = mean + (value - mean) / dn; // double newVar = var + (value - mean) * (value - newMean); // // mean = newMean; // var = newVar / (dn - 1.0); // } else if(count > 1) { // double dd = value - mean; // double newMean = mean + dd / count; // double newVar = var + dd * (value - newMean); // // mean = newMean; // var = newVar; // } else { // mean = value; // var = 0.0; // } // // // Add the value to the buffer // eq.add(value); // // return stdDev(); // } // // public double sma() { return count >= n ? mean : Double.NaN; } // public double var() { return count >= n ? var : Double.NaN; } // public double stdDev() { return count >= n ? Math.sqrt(var) : Double.NaN; } // }
import static org.junit.Assert.*; import net.tradelib.functors.StdDev; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class StdDevTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expectedSma = {null,null,null,null,null,null,null,null,null,"128.175","128.916","129.564","130.278", "131.177","131.764","132.328","132.503","132.656","133.168","133.497"}; String [] expectedStdDev = {null,null,null,null,null,null,null,null,null,"2.75949","2.627907","2.440388", "2.211524","2.065559","1.637371","1.67296","1.685639","1.642269","1.377799","1.202858"};
// Path: src/main/java/net/tradelib/functors/StdDev.java // public class StdDev { // private EvictingQueue<Double> eq; // private double mean; // private double var; // private int count; // private int n; // private double dn; // N as a double // // public StdDev(int n) { // this.mean = 0.0; // this.var = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // this.eq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // double oldMean = mean; // mean += (value - eq.peek()) / dn; // var += (value - mean + eq.peek() - oldMean)*(value - eq.peek()) / (dn - 1.0); // } else if(count == n) { // double newMean = mean + (value - mean) / dn; // double newVar = var + (value - mean) * (value - newMean); // // mean = newMean; // var = newVar / (dn - 1.0); // } else if(count > 1) { // double dd = value - mean; // double newMean = mean + dd / count; // double newVar = var + dd * (value - newMean); // // mean = newMean; // var = newVar; // } else { // mean = value; // var = 0.0; // } // // // Add the value to the buffer // eq.add(value); // // return stdDev(); // } // // public double sma() { return count >= n ? mean : Double.NaN; } // public double var() { return count >= n ? var : Double.NaN; } // public double stdDev() { return count >= n ? Math.sqrt(var) : Double.NaN; } // } // Path: src/test/java/net/tradelib/functors/StdDevTest.java import static org.junit.Assert.*; import net.tradelib.functors.StdDev; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class StdDevTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expectedSma = {null,null,null,null,null,null,null,null,null,"128.175","128.916","129.564","130.278", "131.177","131.764","132.328","132.503","132.656","133.168","133.497"}; String [] expectedStdDev = {null,null,null,null,null,null,null,null,null,"2.75949","2.627907","2.440388", "2.211524","2.065559","1.637371","1.67296","1.685639","1.642269","1.377799","1.202858"};
StdDev sd = new StdDev(10);
ivannp/tradelib
src/test/java/net/tradelib/functors/MinTest.java
// Path: src/main/java/net/tradelib/functors/Min.java // public class Min { // private int length; // private int count; // private EvictingQueue<Double> eq; // // public Min(int length) { // this.length = length; // this.count = 0; // this.eq = EvictingQueue.create(this.length); // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // ++count; // eq.add(value); // } // // public double last() { // return count < length ? Double.NaN : eq.stream().min(Double::compare).get(); // } // }
import static org.junit.Assert.*; import net.tradelib.functors.Min; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class MinTest { @Test public void test() { String [] inputs = { "2024","1990.5","1983.25","1965","2008.25","2060","2067","2072.5","2079","2078.75","2084.25", "2085.75","2076.75","2052.5","2046.25","2016","1994.5","2019.5","2055","2035.25","2022.5","2016","2007.5", "1989","2013","2016.75","2026.5","2056.5","2044","2053.5","2030","1991.5","2018.5","1988.5","2017","2042", "2030","2055","2053","2042.5"}; String [] expected = { null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, "1965","1965","1965","1965","1989","1989","1989","1989","1989","1989","1989","1989","1989","1989","1988.5", "1988.5","1988.5","1988.5","1988.5","1988.5","1988.5"};
// Path: src/main/java/net/tradelib/functors/Min.java // public class Min { // private int length; // private int count; // private EvictingQueue<Double> eq; // // public Min(int length) { // this.length = length; // this.count = 0; // this.eq = EvictingQueue.create(this.length); // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // ++count; // eq.add(value); // } // // public double last() { // return count < length ? Double.NaN : eq.stream().min(Double::compare).get(); // } // } // Path: src/test/java/net/tradelib/functors/MinTest.java import static org.junit.Assert.*; import net.tradelib.functors.Min; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class MinTest { @Test public void test() { String [] inputs = { "2024","1990.5","1983.25","1965","2008.25","2060","2067","2072.5","2079","2078.75","2084.25", "2085.75","2076.75","2052.5","2046.25","2016","1994.5","2019.5","2055","2035.25","2022.5","2016","2007.5", "1989","2013","2016.75","2026.5","2056.5","2044","2053.5","2030","1991.5","2018.5","1988.5","2017","2042", "2030","2055","2053","2042.5"}; String [] expected = { null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, "1965","1965","1965","1965","1989","1989","1989","1989","1989","1989","1989","1989","1989","1989","1988.5", "1988.5","1988.5","1988.5","1988.5","1988.5","1988.5"};
Min mm = new Min(20);
ivannp/tradelib
src/test/java/net/tradelib/functors/PercentileTest.java
// Path: src/main/java/net/tradelib/functors/Percentile.java // public class Percentile { // private int length; // private int count; // private double [] buffer; // private double [] sorted; // private boolean isSorted; // // public Percentile(int length) { // this.length = length; // this.count = 0; // this.buffer = new double [length]; // this.sorted = new double [length]; // this.isSorted = false; // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // buffer[count % length] = value; // ++count; // isSorted = false; // } // // public double last(double percentile) { // if(count < length) return Double.NaN; // // if(!isSorted) { // System.arraycopy(buffer, 0, sorted, 0, length); // Arrays.sort(sorted); // isSorted = true; // } // // double n = (length - 1.0)*percentile + 1.0; // if(n == 1d) { // return sorted[0]; // } else if(n == length) { // return sorted[length - 1]; // } else { // int k = (int)n; // double d = n - k; // return sorted[k - 1] + d * (sorted[k] - sorted[k - 1]); // } // } // }
import static org.junit.Assert.*; import net.tradelib.functors.Percentile; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class PercentileTest { @Test public void test() { Double [] inputs = { 204.97, 205.45, 202.74, 200.14, 201.99, 199.45, 201.92, 204.84, 204.06, 206.12, 205.55, 204.63, 206.81, 206.93, 208.92, 209.78, 210.11, 210.13, 209.98, 211.24 }; Double [] expected = { null, null, null, null, null, null, null, null, null, null, 205.21, 205.145, 205.195, 205.835, 206.465, 206.87, 207.925, 209.35, 209.88, 210.045 };
// Path: src/main/java/net/tradelib/functors/Percentile.java // public class Percentile { // private int length; // private int count; // private double [] buffer; // private double [] sorted; // private boolean isSorted; // // public Percentile(int length) { // this.length = length; // this.count = 0; // this.buffer = new double [length]; // this.sorted = new double [length]; // this.isSorted = false; // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // buffer[count % length] = value; // ++count; // isSorted = false; // } // // public double last(double percentile) { // if(count < length) return Double.NaN; // // if(!isSorted) { // System.arraycopy(buffer, 0, sorted, 0, length); // Arrays.sort(sorted); // isSorted = true; // } // // double n = (length - 1.0)*percentile + 1.0; // if(n == 1d) { // return sorted[0]; // } else if(n == length) { // return sorted[length - 1]; // } else { // int k = (int)n; // double d = n - k; // return sorted[k - 1] + d * (sorted[k] - sorted[k - 1]); // } // } // } // Path: src/test/java/net/tradelib/functors/PercentileTest.java import static org.junit.Assert.*; import net.tradelib.functors.Percentile; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class PercentileTest { @Test public void test() { Double [] inputs = { 204.97, 205.45, 202.74, 200.14, 201.99, 199.45, 201.92, 204.84, 204.06, 206.12, 205.55, 204.63, 206.81, 206.93, 208.92, 209.78, 210.11, 210.13, 209.98, 211.24 }; Double [] expected = { null, null, null, null, null, null, null, null, null, null, 205.21, 205.145, 205.195, 205.835, 206.465, 206.87, 207.925, 209.35, 209.88, 210.045 };
Percentile percentile = new Percentile(11);
ivannp/tradelib
src/test/java/net/tradelib/functors/SmaTest.java
// Path: src/main/java/net/tradelib/functors/Sma.java // public class Sma implements IMovingAverage { // private double mean; // private EvictingQueue<Double> cq; // private final int n; // private final double dn; // private int count; // // public Sma(int n) { // this.count = 0; // this.n = n; // this.dn = n; // this.mean = 0.0; // this.cq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // mean += (value - cq.peek()) / dn; // } else if(count == n) { // mean += (value - mean) / dn; // } else if(count > 1) { // mean += (value - mean) / count; // } else { // mean = value; // } // // // Add the value to the buffer // cq.add(value); // // return last(); // } // // public double last() { return count >= n ? mean : Double.NaN; } // }
import static org.junit.Assert.*; import net.tradelib.functors.Sma; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class SmaTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expected = {null,null,null,null,null,null,null,null,null,"128.175","128.916","129.564","130.278", "131.177","131.764","132.328","132.503","132.656","133.168","133.497"};
// Path: src/main/java/net/tradelib/functors/Sma.java // public class Sma implements IMovingAverage { // private double mean; // private EvictingQueue<Double> cq; // private final int n; // private final double dn; // private int count; // // public Sma(int n) { // this.count = 0; // this.n = n; // this.dn = n; // this.mean = 0.0; // this.cq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // mean += (value - cq.peek()) / dn; // } else if(count == n) { // mean += (value - mean) / dn; // } else if(count > 1) { // mean += (value - mean) / count; // } else { // mean = value; // } // // // Add the value to the buffer // cq.add(value); // // return last(); // } // // public double last() { return count >= n ? mean : Double.NaN; } // } // Path: src/test/java/net/tradelib/functors/SmaTest.java import static org.junit.Assert.*; import net.tradelib.functors.Sma; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class SmaTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expected = {null,null,null,null,null,null,null,null,null,"128.175","128.916","129.564","130.278", "131.177","131.764","132.328","132.503","132.656","133.168","133.497"};
Sma sma = new Sma(10);
ivannp/tradelib
src/test/java/net/tradelib/functors/EmaTest.java
// Path: src/main/java/net/tradelib/functors/Ema.java // public class Ema implements IMovingAverage { // private final int n; // private final double dn; // private double previous; // private int count; // private final double k; // // public Ema(int n) { // this.previous = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // this.k = 2.0 / (this.dn + 1.0); // } // // public Ema(int n, boolean wilder) { // this.previous = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // if(wilder) { // this.k = 1.0 / dn; // } else { // this.k = 2.0 / (this.dn + 1.0); // } // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) { // ++count; // if(count > n) { // previous = value * k + previous * (1.0 - k); // } else if(count == n) { // previous = (previous + value) / dn; // } else { // previous += value; // } // return last(); // } // // public double last() { return count < n ? Double.NaN : previous; } // }
import static org.junit.Assert.*; import net.tradelib.functors.Ema; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class EmaTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expected = {null,null,null,null,null,null,null,null,null,"128.175","128.837727","129.379959", "130.005421","130.897162","131.314042","131.976943","132.235681","132.360103","132.798266","133.082217"};
// Path: src/main/java/net/tradelib/functors/Ema.java // public class Ema implements IMovingAverage { // private final int n; // private final double dn; // private double previous; // private int count; // private final double k; // // public Ema(int n) { // this.previous = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // this.k = 2.0 / (this.dn + 1.0); // } // // public Ema(int n, boolean wilder) { // this.previous = 0.0; // this.count = 0; // this.n = n; // this.dn = n; // if(wilder) { // this.k = 1.0 / dn; // } else { // this.k = 2.0 / (this.dn + 1.0); // } // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) { // ++count; // if(count > n) { // previous = value * k + previous * (1.0 - k); // } else if(count == n) { // previous = (previous + value) / dn; // } else { // previous += value; // } // return last(); // } // // public double last() { return count < n ? Double.NaN : previous; } // } // Path: src/test/java/net/tradelib/functors/EmaTest.java import static org.junit.Assert.*; import net.tradelib.functors.Ema; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class EmaTest { @Test public void test() { String [] inputs = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] expected = {null,null,null,null,null,null,null,null,null,"128.175","128.837727","129.379959", "130.005421","130.897162","131.314042","131.976943","132.235681","132.360103","132.798266","133.082217"};
Ema ema = new Ema(10);
ivannp/tradelib
src/test/java/net/tradelib/functors/AtrTest.java
// Path: src/main/java/net/tradelib/functors/Atr.java // public class Atr { // public enum MaType { SMA, EMA } // private IMovingAverage ima; // private int n; // private double dn; // private double close; // Previous close // int count; // // public Atr(int n) { // this.count = 0; // this.ima = new Ema(n, true); // this.n = n; // this.dn = n; // } // // public Atr(int n, boolean wilder) { // this.count = 0; // this.ima = new Ema(n, wilder); // this.n = n; // this.dn = n; // } // // public Atr(int n, MaType mt) { // this.count = 0; // if(mt == MaType.SMA) { // this.ima = new Sma(n); // } else { // this.ima = new Ema(n, true); // } // this.n = n; // this.dn = n; // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double high, double low, double close) { // // assert high >= low && high >= close && low <= close; // // if(count > 0) { // double trueHigh = Math.max(high, this.close); // double trueLow = Math.min(low, this.close); // ima.add(trueHigh - trueLow); // this.close = close; // } else { // // No previous close - use high/low // // ema_.add(high.subtract(low)); // this.close = close; // } // // ++count; // // return last(); // } // // public double last() { return ima.last(); } // } // // Path: src/main/java/net/tradelib/functors/Atr.java // public enum MaType { SMA, EMA }
import static org.junit.Assert.*; import net.tradelib.functors.Atr; import net.tradelib.functors.Atr.MaType; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class AtrTest { @Test public void test() { String [] close = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] high = {"124.59","125.66","126.21","126.17","127.66","129.63","132.49","131.97","130.37","131.11", "132.31","132.61","134.12","135.03","134.68","135.11","135.59","134.18","135.12","135.19"}; String [] low = {"124.02","124.81","125.53","125.65","126.15","127.96","130.19","130.17","129.42","129.04", "130.92","131.14","132.7","132.68","133.03","134.07","132.96","132.28","134.15","134.05"}; String [] expected = {null,null,null,null,null,null,null,null,null,null,"1.709","1.6851","1.74659","1.806931", "1.814238","1.824814","1.905333","1.904799","1.934319","1.854888"};
// Path: src/main/java/net/tradelib/functors/Atr.java // public class Atr { // public enum MaType { SMA, EMA } // private IMovingAverage ima; // private int n; // private double dn; // private double close; // Previous close // int count; // // public Atr(int n) { // this.count = 0; // this.ima = new Ema(n, true); // this.n = n; // this.dn = n; // } // // public Atr(int n, boolean wilder) { // this.count = 0; // this.ima = new Ema(n, wilder); // this.n = n; // this.dn = n; // } // // public Atr(int n, MaType mt) { // this.count = 0; // if(mt == MaType.SMA) { // this.ima = new Sma(n); // } else { // this.ima = new Ema(n, true); // } // this.n = n; // this.dn = n; // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double high, double low, double close) { // // assert high >= low && high >= close && low <= close; // // if(count > 0) { // double trueHigh = Math.max(high, this.close); // double trueLow = Math.min(low, this.close); // ima.add(trueHigh - trueLow); // this.close = close; // } else { // // No previous close - use high/low // // ema_.add(high.subtract(low)); // this.close = close; // } // // ++count; // // return last(); // } // // public double last() { return ima.last(); } // } // // Path: src/main/java/net/tradelib/functors/Atr.java // public enum MaType { SMA, EMA } // Path: src/test/java/net/tradelib/functors/AtrTest.java import static org.junit.Assert.*; import net.tradelib.functors.Atr; import net.tradelib.functors.Atr.MaType; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class AtrTest { @Test public void test() { String [] close = {"124.41","125.34","125.68","125.92","127.32","129.32","131.65","131.39","129.65","131.07", "131.82","131.82","132.82","134.91","133.19","134.96","133.4","132.92","134.77","134.36"}; String [] high = {"124.59","125.66","126.21","126.17","127.66","129.63","132.49","131.97","130.37","131.11", "132.31","132.61","134.12","135.03","134.68","135.11","135.59","134.18","135.12","135.19"}; String [] low = {"124.02","124.81","125.53","125.65","126.15","127.96","130.19","130.17","129.42","129.04", "130.92","131.14","132.7","132.68","133.03","134.07","132.96","132.28","134.15","134.05"}; String [] expected = {null,null,null,null,null,null,null,null,null,null,"1.709","1.6851","1.74659","1.806931", "1.814238","1.824814","1.905333","1.904799","1.934319","1.854888"};
Atr atr = new Atr(10);
ivannp/tradelib
src/test/java/net/tradelib/functors/AtrTest.java
// Path: src/main/java/net/tradelib/functors/Atr.java // public class Atr { // public enum MaType { SMA, EMA } // private IMovingAverage ima; // private int n; // private double dn; // private double close; // Previous close // int count; // // public Atr(int n) { // this.count = 0; // this.ima = new Ema(n, true); // this.n = n; // this.dn = n; // } // // public Atr(int n, boolean wilder) { // this.count = 0; // this.ima = new Ema(n, wilder); // this.n = n; // this.dn = n; // } // // public Atr(int n, MaType mt) { // this.count = 0; // if(mt == MaType.SMA) { // this.ima = new Sma(n); // } else { // this.ima = new Ema(n, true); // } // this.n = n; // this.dn = n; // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double high, double low, double close) { // // assert high >= low && high >= close && low <= close; // // if(count > 0) { // double trueHigh = Math.max(high, this.close); // double trueLow = Math.min(low, this.close); // ima.add(trueHigh - trueLow); // this.close = close; // } else { // // No previous close - use high/low // // ema_.add(high.subtract(low)); // this.close = close; // } // // ++count; // // return last(); // } // // public double last() { return ima.last(); } // } // // Path: src/main/java/net/tradelib/functors/Atr.java // public enum MaType { SMA, EMA }
import static org.junit.Assert.*; import net.tradelib.functors.Atr; import net.tradelib.functors.Atr.MaType; import org.junit.Test;
String [] expected = {null,null,null,null,null,null,null,null,null,null,"1.709","1.6851","1.74659","1.806931", "1.814238","1.824814","1.905333","1.904799","1.934319","1.854888"}; Atr atr = new Atr(10); for(int ii = 0; ii < close.length; ++ii) { atr.add(Double.parseDouble(high[ii]), Double.parseDouble(low[ii]), Double.parseDouble(close[ii])); double val = atr.last(); if(expected[ii] == null) { assertTrue(Double.isNaN(val)); } else { assertEquals(val, Double.parseDouble(expected[ii]), 1e-6); } } String [] expectedRegular = {null,null,null,null,null,null,null,null,null,null, "1.709","1.665545","1.780901","1.884373","1.883578","1.8902","2.024709","2.002035","2.038029","1.874751"}; atr = new Atr(10, false); for(int ii = 0; ii < close.length; ++ii) { atr.add(Double.parseDouble(high[ii]), Double.parseDouble(low[ii]), Double.parseDouble(close[ii])); double val = atr.last(); if(expectedRegular[ii] == null) { assertTrue(Double.isNaN(val)); } else { assertEquals(val, Double.parseDouble(expectedRegular[ii]), 1e-6); } } String [] expectedSma = {null,null,null,null,null,null,null,null,null,null, "1.709","1.731","1.874","2.057","2.071","2.032","1.978","1.988","2.011","1.918"};
// Path: src/main/java/net/tradelib/functors/Atr.java // public class Atr { // public enum MaType { SMA, EMA } // private IMovingAverage ima; // private int n; // private double dn; // private double close; // Previous close // int count; // // public Atr(int n) { // this.count = 0; // this.ima = new Ema(n, true); // this.n = n; // this.dn = n; // } // // public Atr(int n, boolean wilder) { // this.count = 0; // this.ima = new Ema(n, wilder); // this.n = n; // this.dn = n; // } // // public Atr(int n, MaType mt) { // this.count = 0; // if(mt == MaType.SMA) { // this.ima = new Sma(n); // } else { // this.ima = new Ema(n, true); // } // this.n = n; // this.dn = n; // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double high, double low, double close) { // // assert high >= low && high >= close && low <= close; // // if(count > 0) { // double trueHigh = Math.max(high, this.close); // double trueLow = Math.min(low, this.close); // ima.add(trueHigh - trueLow); // this.close = close; // } else { // // No previous close - use high/low // // ema_.add(high.subtract(low)); // this.close = close; // } // // ++count; // // return last(); // } // // public double last() { return ima.last(); } // } // // Path: src/main/java/net/tradelib/functors/Atr.java // public enum MaType { SMA, EMA } // Path: src/test/java/net/tradelib/functors/AtrTest.java import static org.junit.Assert.*; import net.tradelib.functors.Atr; import net.tradelib.functors.Atr.MaType; import org.junit.Test; String [] expected = {null,null,null,null,null,null,null,null,null,null,"1.709","1.6851","1.74659","1.806931", "1.814238","1.824814","1.905333","1.904799","1.934319","1.854888"}; Atr atr = new Atr(10); for(int ii = 0; ii < close.length; ++ii) { atr.add(Double.parseDouble(high[ii]), Double.parseDouble(low[ii]), Double.parseDouble(close[ii])); double val = atr.last(); if(expected[ii] == null) { assertTrue(Double.isNaN(val)); } else { assertEquals(val, Double.parseDouble(expected[ii]), 1e-6); } } String [] expectedRegular = {null,null,null,null,null,null,null,null,null,null, "1.709","1.665545","1.780901","1.884373","1.883578","1.8902","2.024709","2.002035","2.038029","1.874751"}; atr = new Atr(10, false); for(int ii = 0; ii < close.length; ++ii) { atr.add(Double.parseDouble(high[ii]), Double.parseDouble(low[ii]), Double.parseDouble(close[ii])); double val = atr.last(); if(expectedRegular[ii] == null) { assertTrue(Double.isNaN(val)); } else { assertEquals(val, Double.parseDouble(expectedRegular[ii]), 1e-6); } } String [] expectedSma = {null,null,null,null,null,null,null,null,null,null, "1.709","1.731","1.874","2.057","2.071","2.032","1.978","1.988","2.011","1.918"};
atr = new Atr(10, MaType.SMA);
ivannp/tradelib
src/main/java/net/tradelib/core/BarHistory.java
// Path: src/main/java/net/tradelib/functors/Sma.java // public class Sma implements IMovingAverage { // private double mean; // private EvictingQueue<Double> cq; // private final int n; // private final double dn; // private int count; // // public Sma(int n) { // this.count = 0; // this.n = n; // this.dn = n; // this.mean = 0.0; // this.cq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // mean += (value - cq.peek()) / dn; // } else if(count == n) { // mean += (value - mean) / dn; // } else if(count > 1) { // mean += (value - mean) / count; // } else { // mean = value; // } // // // Add the value to the buffer // cq.add(value); // // return last(); // } // // public double last() { return count >= n ? mean : Double.NaN; } // }
import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import net.tradelib.functors.Sma;
// Copyright 2015 Ivan Popivanov // // 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 net.tradelib.core; public class BarHistory { private List<Bar> bars = new ArrayList<Bar>(); public interface IHistoryData { public double get(int id); } private class MutableData<T> implements IHistoryData { private List<T> list; public MutableData() { list = new ArrayList<T>(); } public void add(T value) { list.add(value); } @Override public double get(int id) { return (Double)list.get(list.size() - id -1); } } public class HistoryData implements IHistoryData { private final IHistoryData container; public HistoryData(IHistoryData container) { this.container = container; } @Override public double get(int id) { return container.get(id); } public double sma(int len) {
// Path: src/main/java/net/tradelib/functors/Sma.java // public class Sma implements IMovingAverage { // private double mean; // private EvictingQueue<Double> cq; // private final int n; // private final double dn; // private int count; // // public Sma(int n) { // this.count = 0; // this.n = n; // this.dn = n; // this.mean = 0.0; // this.cq = EvictingQueue.create(this.n); // } // // public int getLength() { return n; } // public int getCount() { return count; } // // public double add(double value) // { // // The number of elements including the one added // ++count; // if(count > n) { // mean += (value - cq.peek()) / dn; // } else if(count == n) { // mean += (value - mean) / dn; // } else if(count > 1) { // mean += (value - mean) / count; // } else { // mean = value; // } // // // Add the value to the buffer // cq.add(value); // // return last(); // } // // public double last() { return count >= n ? mean : Double.NaN; } // } // Path: src/main/java/net/tradelib/core/BarHistory.java import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import net.tradelib.functors.Sma; // Copyright 2015 Ivan Popivanov // // 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 net.tradelib.core; public class BarHistory { private List<Bar> bars = new ArrayList<Bar>(); public interface IHistoryData { public double get(int id); } private class MutableData<T> implements IHistoryData { private List<T> list; public MutableData() { list = new ArrayList<T>(); } public void add(T value) { list.add(value); } @Override public double get(int id) { return (Double)list.get(list.size() - id -1); } } public class HistoryData implements IHistoryData { private final IHistoryData container; public HistoryData(IHistoryData container) { this.container = container; } @Override public double get(int id) { return container.get(id); } public double sma(int len) {
Sma ff = new Sma(len);
ivannp/tradelib
src/test/java/net/tradelib/functors/MaxTest.java
// Path: src/main/java/net/tradelib/functors/Max.java // public class Max { // private int length; // private int count; // private EvictingQueue<Double> eq; // // public Max(int length) { // this.length = length; // this.count = 0; // this.eq = EvictingQueue.create(this.length); // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // ++count; // eq.add(value); // } // // public double last() { // return count < length ? Double.NaN : eq.stream().max(Double::compare).get(); // } // }
import static org.junit.Assert.*; import net.tradelib.functors.Max; import org.junit.Test;
// Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class MaxTest { @Test public void test() { String [] inputs = { "2024","1990.5","1983.25","1965","2008.25","2060","2067","2072.5","2079","2078.75","2084.25", "2085.75","2076.75","2052.5","2046.25","2016","1994.5","2019.5","2055","2035.25","2022.5","2016","2007.5", "1989","2013","2016.75","2026.5","2056.5","2044","2053.5","2030","1991.5","2018.5","1988.5","2017","2042", "2030","2055","2053","2042.5"}; String [] expected = { null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, "2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75", "2085.75","2076.75","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5"};
// Path: src/main/java/net/tradelib/functors/Max.java // public class Max { // private int length; // private int count; // private EvictingQueue<Double> eq; // // public Max(int length) { // this.length = length; // this.count = 0; // this.eq = EvictingQueue.create(this.length); // } // // public int getLength() { return length; } // public int getCount() { return count; } // // public void add(double value) { // ++count; // eq.add(value); // } // // public double last() { // return count < length ? Double.NaN : eq.stream().max(Double::compare).get(); // } // } // Path: src/test/java/net/tradelib/functors/MaxTest.java import static org.junit.Assert.*; import net.tradelib.functors.Max; import org.junit.Test; // Copyright 2015 by Ivan Popivanov // // 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 net.tradelib.functors; public class MaxTest { @Test public void test() { String [] inputs = { "2024","1990.5","1983.25","1965","2008.25","2060","2067","2072.5","2079","2078.75","2084.25", "2085.75","2076.75","2052.5","2046.25","2016","1994.5","2019.5","2055","2035.25","2022.5","2016","2007.5", "1989","2013","2016.75","2026.5","2056.5","2044","2053.5","2030","1991.5","2018.5","1988.5","2017","2042", "2030","2055","2053","2042.5"}; String [] expected = { null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null, "2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75","2085.75", "2085.75","2076.75","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5","2056.5"};
Max mm = new Max(20);
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/openhab/RestClient.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/connection/OkHttpClientFactory.java // public class OkHttpClientFactory { // private static OkHttpClientFactory ourInstance; // // public Credentials mCred = null; // private String mHost; // private String mRealm; // // public static synchronized OkHttpClientFactory getInstance() { // if (ourInstance == null) { // ourInstance = new OkHttpClientFactory(); // } // return ourInstance; // } // // public OkHttpClient create() { // OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(0, TimeUnit.SECONDS); // // builder.sslSocketFactory(CertificateManager.getInstance().getSocketFactory(), // CertificateManager.getInstance().getTrustManager()) // .hostnameVerifier((s, session) -> { // try { // Certificate[] certificates = session.getPeerCertificates(); // for (Certificate certificate : certificates) { // if (!(certificate instanceof X509Certificate)) { // return false; // } // if (CertificateManager.getInstance().isTrusted((X509Certificate) certificate)) { // return true; // } // } // } catch (SSLException e) { // // return false; // } // return false; // }); // // if (mCred != null) { // // create a copy so it can not be nulled again // Credentials copy = new Credentials(mCred.getUserName(), mCred.getPassword()); // // final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); // final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(copy); // final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(copy); // // // note that all auth schemes should be registered as lowercase! // DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder() // .with("digest", digestAuthenticator) // .with("basic", basicAuthenticator) // .build(); // // builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) // .addInterceptor(new AuthenticationCacheInterceptor(authCache)); // } // // return builder.build(); // } // // public void setAuth(String user, String pass) { // mCred = new Credentials(user, pass); // } // // public void removeAuth() { // mCred = null; // } // // public void setHost(String host) { // mHost = host; // } // // public void setRealm(String realm) { // mRealm = realm; // } // // public String getHost() { // return mHost; // } // // public String getRealm() { // return mRealm; // } // }
import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.io.IOException; import de.vier_bier.habpanelviewer.connection.OkHttpClientFactory; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody;
super("RestClient"); start(); } void getItemState(String serverURL, ISubscriptionListener l, String itemName) { mWorkerHandler.obtainMessage(GET_ID, new ItemSubscription(serverURL, l, itemName)).sendToTarget(); } void setItemState(String serverURL, ItemState itemState) { mWorkerHandler.obtainMessage(SET_ID, new ItemModification(serverURL, itemState)).sendToTarget(); } @Override protected void onLooperPrepared() { super.onLooperPrepared(); mWorkerHandler = new Handler(getLooper(), msg -> { switch (msg.what) { case GET_ID: getRequest((ItemSubscription) msg.obj); break; case SET_ID: putRequest((ItemModification) msg.obj); break; } return true; }); } private void putRequest(ItemModification item) { try {
// Path: app/src/main/java/de/vier_bier/habpanelviewer/connection/OkHttpClientFactory.java // public class OkHttpClientFactory { // private static OkHttpClientFactory ourInstance; // // public Credentials mCred = null; // private String mHost; // private String mRealm; // // public static synchronized OkHttpClientFactory getInstance() { // if (ourInstance == null) { // ourInstance = new OkHttpClientFactory(); // } // return ourInstance; // } // // public OkHttpClient create() { // OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(0, TimeUnit.SECONDS); // // builder.sslSocketFactory(CertificateManager.getInstance().getSocketFactory(), // CertificateManager.getInstance().getTrustManager()) // .hostnameVerifier((s, session) -> { // try { // Certificate[] certificates = session.getPeerCertificates(); // for (Certificate certificate : certificates) { // if (!(certificate instanceof X509Certificate)) { // return false; // } // if (CertificateManager.getInstance().isTrusted((X509Certificate) certificate)) { // return true; // } // } // } catch (SSLException e) { // // return false; // } // return false; // }); // // if (mCred != null) { // // create a copy so it can not be nulled again // Credentials copy = new Credentials(mCred.getUserName(), mCred.getPassword()); // // final Map<String, CachingAuthenticator> authCache = new ConcurrentHashMap<>(); // final BasicAuthenticator basicAuthenticator = new BasicAuthenticator(copy); // final DigestAuthenticator digestAuthenticator = new DigestAuthenticator(copy); // // // note that all auth schemes should be registered as lowercase! // DispatchingAuthenticator authenticator = new DispatchingAuthenticator.Builder() // .with("digest", digestAuthenticator) // .with("basic", basicAuthenticator) // .build(); // // builder.authenticator(new CachingAuthenticatorDecorator(authenticator, authCache)) // .addInterceptor(new AuthenticationCacheInterceptor(authCache)); // } // // return builder.build(); // } // // public void setAuth(String user, String pass) { // mCred = new Credentials(user, pass); // } // // public void removeAuth() { // mCred = null; // } // // public void setHost(String host) { // mHost = host; // } // // public void setRealm(String realm) { // mRealm = realm; // } // // public String getHost() { // return mHost; // } // // public String getRealm() { // return mRealm; // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/openhab/RestClient.java import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import java.io.IOException; import de.vier_bier.habpanelviewer.connection.OkHttpClientFactory; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; super("RestClient"); start(); } void getItemState(String serverURL, ISubscriptionListener l, String itemName) { mWorkerHandler.obtainMessage(GET_ID, new ItemSubscription(serverURL, l, itemName)).sendToTarget(); } void setItemState(String serverURL, ItemState itemState) { mWorkerHandler.obtainMessage(SET_ID, new ItemModification(serverURL, itemState)).sendToTarget(); } @Override protected void onLooperPrepared() { super.onLooperPrepared(); mWorkerHandler = new Handler(getLooper(), msg -> { switch (msg.what) { case GET_ID: getRequest((ItemSubscription) msg.obj); break; case SET_ID: putRequest((ItemModification) msg.obj); break; } return true; }); } private void putRequest(ItemModification item) { try {
OkHttpClient client = OkHttpClientFactory.getInstance().create();
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/AppRestartingExceptionHandler.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/status/ApplicationStatus.java // public class ApplicationStatus { // private final ArrayList<StatusItem> mValues = new ArrayList<>(); // private final HashMap<String, StatusItem> mIndices = new HashMap<>(); // // public synchronized void set(String key, String value) { // StatusItem item = mIndices.get(key); // if (item == null) { // item = new StatusItem(key, value); // mValues.add(item); // mIndices.put(key, item); // } else { // item.setValue(value); // } // } // // int getItemCount() { // return mValues.size(); // } // // StatusItem getItem(int i) { // return mValues.get(i); // } // }
import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.jakewharton.processphoenix.ProcessPhoenix; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import de.vier_bier.habpanelviewer.status.ApplicationStatus;
package de.vier_bier.habpanelviewer; /** * UncaughtExceptionHandler that restarts the app in case of exceptions. */ class AppRestartingExceptionHandler implements Thread.UncaughtExceptionHandler { private static final String TAG = "HPV-AppRestartingExHa"; private final MainActivity mCtx; private final int mCount; private int mMaxRestarts; private boolean mRestartEnabled; private final Thread.UncaughtExceptionHandler mDefaultHandler; AppRestartingExceptionHandler(MainActivity context, Thread.UncaughtExceptionHandler defaultHandler, int restartCount) { mCtx = context; mDefaultHandler = defaultHandler; mCount = restartCount; EventBus.getDefault().register(this); Thread.setDefaultUncaughtExceptionHandler(this); } @Subscribe(threadMode = ThreadMode.MAIN)
// Path: app/src/main/java/de/vier_bier/habpanelviewer/status/ApplicationStatus.java // public class ApplicationStatus { // private final ArrayList<StatusItem> mValues = new ArrayList<>(); // private final HashMap<String, StatusItem> mIndices = new HashMap<>(); // // public synchronized void set(String key, String value) { // StatusItem item = mIndices.get(key); // if (item == null) { // item = new StatusItem(key, value); // mValues.add(item); // mIndices.put(key, item); // } else { // item.setValue(value); // } // } // // int getItemCount() { // return mValues.size(); // } // // StatusItem getItem(int i) { // return mValues.get(i); // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/AppRestartingExceptionHandler.java import android.content.Intent; import android.content.SharedPreferences; import android.util.Log; import com.jakewharton.processphoenix.ProcessPhoenix; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import de.vier_bier.habpanelviewer.status.ApplicationStatus; package de.vier_bier.habpanelviewer; /** * UncaughtExceptionHandler that restarts the app in case of exceptions. */ class AppRestartingExceptionHandler implements Thread.UncaughtExceptionHandler { private static final String TAG = "HPV-AppRestartingExHa"; private final MainActivity mCtx; private final int mCount; private int mMaxRestarts; private boolean mRestartEnabled; private final Thread.UncaughtExceptionHandler mDefaultHandler; AppRestartingExceptionHandler(MainActivity context, Thread.UncaughtExceptionHandler defaultHandler, int restartCount) { mCtx = context; mDefaultHandler = defaultHandler; mCount = restartCount; EventBus.getDefault().register(this); Thread.setDefaultUncaughtExceptionHandler(this); } @Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ApplicationStatus status) {
vbier/habpanelviewer
app/src/main/java/de/vier_bier/habpanelviewer/command/AdminHandler.java
// Path: app/src/main/java/de/vier_bier/habpanelviewer/AdminReceiver.java // public class AdminReceiver extends DeviceAdminReceiver { // public static final ComponentName COMP = // new ComponentName("de.vier_bier.habpanelviewer", "de.vier_bier.habpanelviewer.AdminReceiver"); // // public AdminReceiver() { // } // }
import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.Context; import de.vier_bier.habpanelviewer.AdminReceiver;
package de.vier_bier.habpanelviewer.command; /** * Handler for ADMIN_LOCK_SCREEN command. */ public class AdminHandler implements ICommandHandler { private final DevicePolicyManager mDPM; public AdminHandler(Activity activity) { mDPM = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); } @Override public boolean handleCommand(Command cmd) { final String cmdStr = cmd.getCommand(); if ("ADMIN_LOCK_SCREEN".equals(cmdStr)) {
// Path: app/src/main/java/de/vier_bier/habpanelviewer/AdminReceiver.java // public class AdminReceiver extends DeviceAdminReceiver { // public static final ComponentName COMP = // new ComponentName("de.vier_bier.habpanelviewer", "de.vier_bier.habpanelviewer.AdminReceiver"); // // public AdminReceiver() { // } // } // Path: app/src/main/java/de/vier_bier/habpanelviewer/command/AdminHandler.java import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.Context; import de.vier_bier.habpanelviewer.AdminReceiver; package de.vier_bier.habpanelviewer.command; /** * Handler for ADMIN_LOCK_SCREEN command. */ public class AdminHandler implements ICommandHandler { private final DevicePolicyManager mDPM; public AdminHandler(Activity activity) { mDPM = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE); } @Override public boolean handleCommand(Command cmd) { final String cmdStr = cmd.getCommand(); if ("ADMIN_LOCK_SCREEN".equals(cmdStr)) {
if (mDPM.isAdminActive(AdminReceiver.COMP)) {