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
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface GetSubjectListUseCase extends Interactor { interface Callback{
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; import java.util.Collection; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface GetSubjectListUseCase extends Interactor { interface Callback{
void onSubjectListLoaded(Collection<Subject> subjects);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; import java.util.Collection;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface GetSubjectListUseCase extends Interactor { interface Callback{ void onSubjectListLoaded(Collection<Subject> subjects);
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; import java.util.Collection; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface GetSubjectListUseCase extends Interactor { interface Callback{ void onSubjectListLoaded(Collection<Subject> subjects);
void onError(SubjectException exception);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/MainActivity.java
// Path: app/src/main/java/com/tonilopezmr/sample/di/BaseActivity.java // public abstract class BaseActivity extends Activity{ // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // injectDependencies(); // // injectViews(); //TODO no funciona en BaseActivity // } // // private void injectDependencies() { // SubjectsApplication application = (SubjectsApplication)getApplication(); // application.inject(this); // } // // private void injectViews(){ // ButterKnife.inject(this); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java // public interface SubjectListPresenter extends Presenter{ // // void setView(SubjectListView view); // // public void onClickItem(SubjectViewModel SubjectModel); // public void onLongItemClick(SubjectViewModel subjectModel); // public void onRetryButtonClick(); // // public void onFloatingButtonClick(SubjectViewModel subjectViewModel); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.getbase.floatingactionbutton.FloatingActionButton; import com.tonilopezmr.sample.R; import com.tonilopezmr.sample.di.BaseActivity; import com.tonilopezmr.sample.ui.presenter.SubjectListPresenter; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.Collection; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tonilopezmr.sample.ui; public class MainActivity extends BaseActivity implements SubjectListView { @Inject
// Path: app/src/main/java/com/tonilopezmr/sample/di/BaseActivity.java // public abstract class BaseActivity extends Activity{ // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // injectDependencies(); // // injectViews(); //TODO no funciona en BaseActivity // } // // private void injectDependencies() { // SubjectsApplication application = (SubjectsApplication)getApplication(); // application.inject(this); // } // // private void injectViews(){ // ButterKnife.inject(this); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java // public interface SubjectListPresenter extends Presenter{ // // void setView(SubjectListView view); // // public void onClickItem(SubjectViewModel SubjectModel); // public void onLongItemClick(SubjectViewModel subjectModel); // public void onRetryButtonClick(); // // public void onFloatingButtonClick(SubjectViewModel subjectViewModel); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/MainActivity.java import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.getbase.floatingactionbutton.FloatingActionButton; import com.tonilopezmr.sample.R; import com.tonilopezmr.sample.di.BaseActivity; import com.tonilopezmr.sample.ui.presenter.SubjectListPresenter; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.Collection; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.tonilopezmr.sample.ui; public class MainActivity extends BaseActivity implements SubjectListView { @Inject
SubjectListPresenter presenter;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/ui/MainActivity.java
// Path: app/src/main/java/com/tonilopezmr/sample/di/BaseActivity.java // public abstract class BaseActivity extends Activity{ // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // injectDependencies(); // // injectViews(); //TODO no funciona en BaseActivity // } // // private void injectDependencies() { // SubjectsApplication application = (SubjectsApplication)getApplication(); // application.inject(this); // } // // private void injectViews(){ // ButterKnife.inject(this); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java // public interface SubjectListPresenter extends Presenter{ // // void setView(SubjectListView view); // // public void onClickItem(SubjectViewModel SubjectModel); // public void onLongItemClick(SubjectViewModel subjectModel); // public void onRetryButtonClick(); // // public void onFloatingButtonClick(SubjectViewModel subjectViewModel); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // }
import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.getbase.floatingactionbutton.FloatingActionButton; import com.tonilopezmr.sample.R; import com.tonilopezmr.sample.di.BaseActivity; import com.tonilopezmr.sample.ui.presenter.SubjectListPresenter; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.Collection; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.tonilopezmr.sample.ui; public class MainActivity extends BaseActivity implements SubjectListView { @Inject SubjectListPresenter presenter; @InjectView(R.id.my_recycler_view) RecyclerView recyclerView; @InjectView(R.id.progress_bar) ProgressBarCircularIndeterminate progressBar; @InjectView(R.id.layout_error) LinearLayout layoutError; @InjectView(R.id.floating_button) FloatingActionButton floatingButton; @InjectView(R.id.retry_btn) Button retryButton; MyRecyclerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); inicializeRecyclerView(recyclerView); init(); } private void init(){ presenter.setView(this); floatingButton.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(android.view.View v) {
// Path: app/src/main/java/com/tonilopezmr/sample/di/BaseActivity.java // public abstract class BaseActivity extends Activity{ // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // injectDependencies(); // // injectViews(); //TODO no funciona en BaseActivity // } // // private void injectDependencies() { // SubjectsApplication application = (SubjectsApplication)getApplication(); // application.inject(this); // } // // private void injectViews(){ // ButterKnife.inject(this); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/presenter/SubjectListPresenter.java // public interface SubjectListPresenter extends Presenter{ // // void setView(SubjectListView view); // // public void onClickItem(SubjectViewModel SubjectModel); // public void onLongItemClick(SubjectViewModel subjectModel); // public void onRetryButtonClick(); // // public void onFloatingButtonClick(SubjectViewModel subjectViewModel); // } // // Path: app/src/main/java/com/tonilopezmr/sample/ui/viewmodel/SubjectViewModelImp.java // public class SubjectViewModelImp implements SubjectViewModel { // // private Subject subject; // // public SubjectViewModelImp(String name) { // subject = new Subject(name); // } // // public SubjectViewModelImp(Subject subject) { // this.subject = subject; // } // // public int getId(){ // return this.subject.getId(); // } // // public String getName(){ // return this.subject.getName(); // } // // @Override // public boolean equals(Object o) { // boolean result = false; // if (o instanceof SubjectViewModel){ // SubjectViewModel model = (SubjectViewModel)o; // if (this.subject.getId() == model.getId() && this.subject.getName().equals(model.getName())){ // result = true; // } // } // return result; // } // // @Override // public String toString() { // return subject.getId()+" "+subject.getName(); // } // } // Path: app/src/main/java/com/tonilopezmr/sample/ui/MainActivity.java import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; import com.gc.materialdesign.views.ProgressBarCircularIndeterminate; import com.getbase.floatingactionbutton.FloatingActionButton; import com.tonilopezmr.sample.R; import com.tonilopezmr.sample.di.BaseActivity; import com.tonilopezmr.sample.ui.presenter.SubjectListPresenter; import com.tonilopezmr.sample.ui.view.SubjectListView; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModel; import com.tonilopezmr.sample.ui.viewmodel.SubjectViewModelImp; import java.util.Collection; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.tonilopezmr.sample.ui; public class MainActivity extends BaseActivity implements SubjectListView { @Inject SubjectListPresenter presenter; @InjectView(R.id.my_recycler_view) RecyclerView recyclerView; @InjectView(R.id.progress_bar) ProgressBarCircularIndeterminate progressBar; @InjectView(R.id.layout_error) LinearLayout layoutError; @InjectView(R.id.floating_button) FloatingActionButton floatingButton; @InjectView(R.id.retry_btn) Button retryButton; MyRecyclerAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); inicializeRecyclerView(recyclerView); init(); } private void init(){ presenter.setView(this); floatingButton.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(android.view.View v) {
presenter.onFloatingButtonClick(new SubjectViewModelImp("New Subject"));
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import java.util.Collection;
package com.tonilopezmr.sample.domain.repository; /** * @author toni. */ public interface SubjectRepository { interface SubjectListCallback {
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import java.util.Collection; package com.tonilopezmr.sample.domain.repository; /** * @author toni. */ public interface SubjectRepository { interface SubjectListCallback {
void onSubjectListLoader(Collection<Subject> subjects);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import java.util.Collection;
package com.tonilopezmr.sample.domain.repository; /** * @author toni. */ public interface SubjectRepository { interface SubjectListCallback { void onSubjectListLoader(Collection<Subject> subjects);
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import java.util.Collection; package com.tonilopezmr.sample.domain.repository; /** * @author toni. */ public interface SubjectRepository { interface SubjectListCallback { void onSubjectListLoader(Collection<Subject> subjects);
void onError(SubjectException subjectException);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface SubjectUseCase extends Interactor { interface Callback {
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface SubjectUseCase extends Interactor { interface Callback {
void onMissionAccomplished(Subject subject);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // }
import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface SubjectUseCase extends Interactor { interface Callback { void onMissionAccomplished(Subject subject);
// Path: app/src/main/java/com/tonilopezmr/sample/domain/Subject.java // public class Subject { // // private int id; // private String name; // // public Subject(String name) { // this.name = name; // } // // public Subject(int id, String name) { // this.id = id; // this.name = name; // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // @Override // public String toString() { // return "ID: "+this.id+" Subject: "+this.name; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/exception/SubjectException.java // public class SubjectException extends RuntimeException { // // private String message; // // public SubjectException(String detailMessage) { // super(detailMessage); // this.message = detailMessage; // } // // public SubjectException(Exception exception) { // this.setStackTrace(exception.getStackTrace()); // this.message = exception.getMessage(); // } // // @Override // public String getMessage() { // return message; // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Interactor.java // public interface Interactor extends Runnable{ // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java import com.tonilopezmr.sample.domain.Subject; import com.tonilopezmr.sample.domain.exception.SubjectException; import com.tonilopezmr.sample.executor.Interactor; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public interface SubjectUseCase extends Interactor { interface Callback { void onMissionAccomplished(Subject subject);
void onError(SubjectException ex);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public abstract class AbstractSubjectUseCase implements SubjectUseCase { protected Executor executor;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public abstract class AbstractSubjectUseCase implements SubjectUseCase { protected Executor executor;
protected MainThread mainThread;
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread;
package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public abstract class AbstractSubjectUseCase implements SubjectUseCase { protected Executor executor; protected MainThread mainThread;
// Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/AbstractSubjectUseCase.java import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; package com.tonilopezmr.sample.domain.interactor; /** * @author toni. */ public abstract class AbstractSubjectUseCase implements SubjectUseCase { protected Executor executor; protected MainThread mainThread;
protected SubjectRepository subjectRepository;
tonilopezmr/Android-EasySQLite
easysqlite/src/main/java/com/tonilopezmr/easysqlite/SQLiteHelper.java
// Path: easysqlite/src/main/java/com/tonilopezmr/easysqlite/exception/SQLiteHelperException.java // public class SQLiteHelperException extends Exception { // // public SQLiteHelperException(String detailMessage) { // super(detailMessage); // } // }
import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.tonilopezmr.easysqlite.exception.SQLiteHelperException;
/* * Copyright 2015 Antonio López Marín <tonilopezmr.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tonilopezmr.easysqlite; /** * @author Antonio López Marín */ public final class SQLiteHelper extends SQLiteOpenHelper{ private Builder builder; private SQLiteHelper(Builder builder) { super(builder.context, builder.databaseName, builder.factory, builder.databaseVersion); this.builder = builder; } /** * Database version. * * @return the version of database SQLite. */ public int getDatabaseVersion(){ return builder.databaseVersion; } /** * If the foreign keys in SQLite are enable. * * @return true if the foreign keys are enable or false if it is not the case. */ public boolean isOnForeignKey(){ return builder.isOnForeignKey; } private void executePragma(SQLiteDatabase db){ if (builder.isOnForeignKey) db.execSQL(Builder.FOREIGN_KEY_ON); } /** * Called when the database is created for the first time. This is where the * creation of tables and the initial population of the tables should happen. * * @param db The database. */ @Override public void onCreate(SQLiteDatabase db) { try { if(builder.tables == null){
// Path: easysqlite/src/main/java/com/tonilopezmr/easysqlite/exception/SQLiteHelperException.java // public class SQLiteHelperException extends Exception { // // public SQLiteHelperException(String detailMessage) { // super(detailMessage); // } // } // Path: easysqlite/src/main/java/com/tonilopezmr/easysqlite/SQLiteHelper.java import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import com.tonilopezmr.easysqlite.exception.SQLiteHelperException; /* * Copyright 2015 Antonio López Marín <tonilopezmr.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tonilopezmr.easysqlite; /** * @author Antonio López Marín */ public final class SQLiteHelper extends SQLiteOpenHelper{ private Builder builder; private SQLiteHelper(Builder builder) { super(builder.context, builder.databaseName, builder.factory, builder.databaseVersion); this.builder = builder; } /** * Database version. * * @return the version of database SQLite. */ public int getDatabaseVersion(){ return builder.databaseVersion; } /** * If the foreign keys in SQLite are enable. * * @return true if the foreign keys are enable or false if it is not the case. */ public boolean isOnForeignKey(){ return builder.isOnForeignKey; } private void executePragma(SQLiteDatabase db){ if (builder.isOnForeignKey) db.execSQL(Builder.FOREIGN_KEY_ON); } /** * Called when the database is created for the first time. This is where the * creation of tables and the initial population of the tables should happen. * * @param db The database. */ @Override public void onCreate(SQLiteDatabase db) { try { if(builder.tables == null){
throw new SQLiteHelperException("The array of String tables can't be null!!");
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides
public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
return new DeleteSubjectUseCaseImp(executor, mainThread, subjectRepository);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new DeleteSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Named("create usecase") @Provides public SubjectUseCase provideCreateSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new DeleteSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Named("create usecase") @Provides public SubjectUseCase provideCreateSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
return new CreateSubjectUseCaseImp(executor, mainThread, subjectRepository);
tonilopezmr/Android-EasySQLite
app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // }
import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides;
package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new DeleteSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Named("create usecase") @Provides public SubjectUseCase provideCreateSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new CreateSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Provides
// Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/DeleteSubjectUseCaseImp.java // public class DeleteSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public DeleteSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // super.subjectRepository.deleteSubject(subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // DeleteSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/SubjectUseCase.java // public interface SubjectUseCase extends Interactor { // // interface Callback { // void onMissionAccomplished(Subject subject); // void onError(SubjectException ex); // } // // public void execute(Subject subject, final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/CreateSubjectUseCaseImp.java // public class CreateSubjectUseCaseImp extends AbstractSubjectUseCase implements SubjectUseCase { // // private Callback callback; // private Subject subject; // // public CreateSubjectUseCaseImp(Executor executor, MainThread mainThread, SubjectRepository subjectRepository) { // super(executor, mainThread, subjectRepository); // } // // @Override // public void execute(Subject subject, final Callback callback) { // if (callback == null){ // throw new IllegalArgumentException("Callback parameter can't be null"); // } // // this.callback = callback; // this.subject = subject; // super.executor.run(this); // } // // // //Interactor Use case // @Override // public void run() { // try { // Thread.sleep(1000); // } catch (InterruptedException e) { // e.printStackTrace(); // } // // super.subjectRepository.createSubject(this.subject, new SubjectRepository.SubjectUseCase() { // @Override // public void onMissionAccomplished(final Subject subject) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onMissionAccomplished(subject); // } // }); // } // // @Override // public void onError(final SubjectException subjectException) { // CreateSubjectUseCaseImp.super.mainThread.post(new Runnable() { // @Override // public void run() { // callback.onError(subjectException); // } // }); // } // }); // } // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/interactor/GetSubjectListUseCase.java // public interface GetSubjectListUseCase extends Interactor { // // interface Callback{ // void onSubjectListLoaded(Collection<Subject> subjects); // void onError(SubjectException exception); // } // // public void execute(final Callback callback); // } // // Path: app/src/main/java/com/tonilopezmr/sample/domain/repository/SubjectRepository.java // public interface SubjectRepository { // // interface SubjectListCallback { // void onSubjectListLoader(Collection<Subject> subjects); // void onError(SubjectException subjectException); // } // // interface SubjectUseCase { // void onMissionAccomplished(Subject subject); // void onError(SubjectException subjectException); // } // // void getSubjectsCollection(SubjectListCallback callback) throws SubjectException; // // void createSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // void deleteSubject(Subject subject, SubjectUseCase callback) throws SubjectException; // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/Executor.java // public interface Executor { // void run(final Interactor interactor); // } // // Path: app/src/main/java/com/tonilopezmr/sample/executor/MainThread.java // public interface MainThread { // void post(final Runnable runnable); // } // Path: app/src/main/java/com/tonilopezmr/sample/di/modules/InteractorModule.java import com.tonilopezmr.sample.domain.interactor.DeleteSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.SubjectUseCase; import com.tonilopezmr.sample.domain.interactor.CreateSubjectUseCaseImp; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCase; import com.tonilopezmr.sample.domain.interactor.GetSubjectListUseCaseImp; import com.tonilopezmr.sample.domain.repository.SubjectRepository; import com.tonilopezmr.sample.executor.Executor; import com.tonilopezmr.sample.executor.MainThread; import javax.inject.Named; import dagger.Module; import dagger.Provides; package com.tonilopezmr.sample.di.modules; /** * * @author Toni */ @Module( complete = false, library = true ) public final class InteractorModule { @Named("delete usecase") @Provides public SubjectUseCase provideDeleteSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new DeleteSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Named("create usecase") @Provides public SubjectUseCase provideCreateSubjectUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){ return new CreateSubjectUseCaseImp(executor, mainThread, subjectRepository); } @Provides
public GetSubjectListUseCase provideGetSubjectListUseCase(Executor executor, MainThread mainThread, @Named("internal_database")SubjectRepository subjectRepository){
Zahusek/TinyProtocolAPI
com/gmail/zahusek/tinyprotocolapi/listener/PacketID.java
// Path: com/gmail/zahusek/tinyprotocolapi/element/PacketType.java // public enum PacketType // { // PacketHandshakingInSetProtocol, // PacketLoginInStart, // PacketLoginInEncryptionBegin, // PacketLoginOutDisconnect, // PacketLoginOutEncryptionBegin, // PacketLoginOutSuccess, // PacketLoginOutSetCompression, // // PacketPlayInAbilities, // PacketPlayInArmAnimation, // PacketPlayInBlockDig, // PacketPlayInBlockPlace, // PacketPlayInChat, // PacketPlayInClientCommand, // PacketPlayInCloseWindow, // PacketPlayInCustomPayload, // PacketPlayInEnchantItem, // PacketPlayInEntityAction, // PacketPlayInFlying, // PacketPlayInLook, // PacketPlayInPosition, // PacketPlayInPositionLook, // PacketPlayInHeldItemSlot, // PacketPlayInKeepAlive, // PacketPlayInResourcePackStatus, // PacketPlayInSetCreativeSlot, // PacketPlayInSettings, // PacketPlayInSpectate, // PacketPlayInSteerVehicle, // PacketPlayInTabComplete, // PacketPlayInTransaction, // PacketPlayInUpdateSign, // PacketPlayInUseEntity, // PacketPlayInWindowClick, // // PacketPlayOutAbilities, // PacketPlayOutAnimation, // PacketPlayOutAttachEntity, // PacketPlayOutBed, // PacketPlayOutBlockAction, // PacketPlayOutBlockBreakAnimation, // PacketPlayOutBlockChange, // PacketPlayOutCamera, // PacketPlayOutChat, // PacketPlayOutCloseWindow, // PacketPlayOutCollect, // PacketPlayOutCombatEvent, // PacketPlayOutCustomPayload, // PacketPlayOutEntity, // PacketPlayOutEntityLook, // PacketPlayOutRelEntityMove, // PacketPlayOutRelEntityMoveLook, // PacketPlayOutEntityDestroy, // PacketPlayOutEntityEffect, // PacketPlayOutEntityEquipment, // PacketPlayOutEntityHeadRotation, // PacketPlayOutEntityMetadata, // PacketPlayOutEntityStatus, // PacketPlayOutEntityTeleport, // PacketPlayOutEntityVelocity, // PacketPlayOutExperience, // PacketPlayOutExplosion, // PacketPlayOutGameStateChange, // PacketPlayOutHeldItemSlot, // PacketPlayOutKeepAlive, // PacketPlayOutKickDisconnect, // PacketPlayOutLogin, // PacketPlayOutMap, // PacketPlayOutMapChunk, // PacketPlayOutMapChunkBulk, // PacketPlayOutMultiBlockChange, // PacketPlayOutNamedEntitySpawn, // PacketPlayOutNamedSoundEffect, // PacketPlayOutOpenSignEditor, // PacketPlayOutOpenWindow, // PacketPlayOutPlayerInfo, // PacketPlayOutPlayerListHeaderFooter, // PacketPlayOutPosition, // PacketPlayOutRemoveEntityEffect, // PacketPlayOutResourcePackSend, // PacketPlayOutRespawn, // PacketPlayOutScoreboardDisplayObjective, // PacketPlayOutScoreboardObjective, // PacketPlayOutScoreboardScore, // PacketPlayOutScoreboardTeam, // PacketPlayOutServerDifficulty, // PacketPlayOutSetCompression, // PacketPlayOutSetSlot, // PacketPlayOutSpawnEntity, // PacketPlayOutSpawnEntityExperienceOrb, // PacketPlayOutSpawnEntityLiving, // PacketPlayOutSpawnEntityPainting, // PacketPlayOutSpawnEntityWeather, // PacketPlayOutSpawnPosition, // PacketPlayOutStatistic, // PacketPlayOutTabComplete, // PacketPlayOutTileEntityData, // PacketPlayOutTitle, // PacketPlayOutTransaction, // PacketPlayOutUpdateAttributes, // PacketPlayOutUpdateEntityNBT, // PacketPlayOutUpdateHealth, // PacketPlayOutUpdateSign, // PacketPlayOutUpdateTime, // PacketPlayOutWindowData, // PacketPlayOutWindowItems, // PacketPlayOutWorldBorder, // PacketPlayOutWorldEvent, // PacketPlayOutWorldParticles, // // PacketStatusInPing, // PacketStatusInStart, // // PacketStatusOutPong, // PacketStatusOutServerInfo; // // public boolean equalsClient () // { // return name().startsWith("PacketPlayIn") || // name().startsWith("PacketStatusIn") || // name().startsWith("PacketLoginIn") || // name().startsWith("PacketHandshakingIn"); // } // // public boolean equalsServer () // { // return name().startsWith("PacketPlayOut") || // name().startsWith("PacketStatusOut") || // name().startsWith("PacketLoginOut"); // } // // }
import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.gmail.zahusek.tinyprotocolapi.element.PacketType;
package com.gmail.zahusek.tinyprotocolapi.listener; @Target({TYPE}) @Retention(RUNTIME) public @interface PacketID
// Path: com/gmail/zahusek/tinyprotocolapi/element/PacketType.java // public enum PacketType // { // PacketHandshakingInSetProtocol, // PacketLoginInStart, // PacketLoginInEncryptionBegin, // PacketLoginOutDisconnect, // PacketLoginOutEncryptionBegin, // PacketLoginOutSuccess, // PacketLoginOutSetCompression, // // PacketPlayInAbilities, // PacketPlayInArmAnimation, // PacketPlayInBlockDig, // PacketPlayInBlockPlace, // PacketPlayInChat, // PacketPlayInClientCommand, // PacketPlayInCloseWindow, // PacketPlayInCustomPayload, // PacketPlayInEnchantItem, // PacketPlayInEntityAction, // PacketPlayInFlying, // PacketPlayInLook, // PacketPlayInPosition, // PacketPlayInPositionLook, // PacketPlayInHeldItemSlot, // PacketPlayInKeepAlive, // PacketPlayInResourcePackStatus, // PacketPlayInSetCreativeSlot, // PacketPlayInSettings, // PacketPlayInSpectate, // PacketPlayInSteerVehicle, // PacketPlayInTabComplete, // PacketPlayInTransaction, // PacketPlayInUpdateSign, // PacketPlayInUseEntity, // PacketPlayInWindowClick, // // PacketPlayOutAbilities, // PacketPlayOutAnimation, // PacketPlayOutAttachEntity, // PacketPlayOutBed, // PacketPlayOutBlockAction, // PacketPlayOutBlockBreakAnimation, // PacketPlayOutBlockChange, // PacketPlayOutCamera, // PacketPlayOutChat, // PacketPlayOutCloseWindow, // PacketPlayOutCollect, // PacketPlayOutCombatEvent, // PacketPlayOutCustomPayload, // PacketPlayOutEntity, // PacketPlayOutEntityLook, // PacketPlayOutRelEntityMove, // PacketPlayOutRelEntityMoveLook, // PacketPlayOutEntityDestroy, // PacketPlayOutEntityEffect, // PacketPlayOutEntityEquipment, // PacketPlayOutEntityHeadRotation, // PacketPlayOutEntityMetadata, // PacketPlayOutEntityStatus, // PacketPlayOutEntityTeleport, // PacketPlayOutEntityVelocity, // PacketPlayOutExperience, // PacketPlayOutExplosion, // PacketPlayOutGameStateChange, // PacketPlayOutHeldItemSlot, // PacketPlayOutKeepAlive, // PacketPlayOutKickDisconnect, // PacketPlayOutLogin, // PacketPlayOutMap, // PacketPlayOutMapChunk, // PacketPlayOutMapChunkBulk, // PacketPlayOutMultiBlockChange, // PacketPlayOutNamedEntitySpawn, // PacketPlayOutNamedSoundEffect, // PacketPlayOutOpenSignEditor, // PacketPlayOutOpenWindow, // PacketPlayOutPlayerInfo, // PacketPlayOutPlayerListHeaderFooter, // PacketPlayOutPosition, // PacketPlayOutRemoveEntityEffect, // PacketPlayOutResourcePackSend, // PacketPlayOutRespawn, // PacketPlayOutScoreboardDisplayObjective, // PacketPlayOutScoreboardObjective, // PacketPlayOutScoreboardScore, // PacketPlayOutScoreboardTeam, // PacketPlayOutServerDifficulty, // PacketPlayOutSetCompression, // PacketPlayOutSetSlot, // PacketPlayOutSpawnEntity, // PacketPlayOutSpawnEntityExperienceOrb, // PacketPlayOutSpawnEntityLiving, // PacketPlayOutSpawnEntityPainting, // PacketPlayOutSpawnEntityWeather, // PacketPlayOutSpawnPosition, // PacketPlayOutStatistic, // PacketPlayOutTabComplete, // PacketPlayOutTileEntityData, // PacketPlayOutTitle, // PacketPlayOutTransaction, // PacketPlayOutUpdateAttributes, // PacketPlayOutUpdateEntityNBT, // PacketPlayOutUpdateHealth, // PacketPlayOutUpdateSign, // PacketPlayOutUpdateTime, // PacketPlayOutWindowData, // PacketPlayOutWindowItems, // PacketPlayOutWorldBorder, // PacketPlayOutWorldEvent, // PacketPlayOutWorldParticles, // // PacketStatusInPing, // PacketStatusInStart, // // PacketStatusOutPong, // PacketStatusOutServerInfo; // // public boolean equalsClient () // { // return name().startsWith("PacketPlayIn") || // name().startsWith("PacketStatusIn") || // name().startsWith("PacketLoginIn") || // name().startsWith("PacketHandshakingIn"); // } // // public boolean equalsServer () // { // return name().startsWith("PacketPlayOut") || // name().startsWith("PacketStatusOut") || // name().startsWith("PacketLoginOut"); // } // // } // Path: com/gmail/zahusek/tinyprotocolapi/listener/PacketID.java import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.gmail.zahusek.tinyprotocolapi.element.PacketType; package com.gmail.zahusek.tinyprotocolapi.listener; @Target({TYPE}) @Retention(RUNTIME) public @interface PacketID
{ PacketType id (); }
Zahusek/TinyProtocolAPI
com/gmail/zahusek/test/example/ExampleListener.java
// Path: com/gmail/zahusek/tinyprotocolapi/listener/PacketListener.java // public interface PacketListener {} // // Path: com/gmail/zahusek/tinyprotocolapi/listener/PacketPriority.java // public enum PacketPriority // {LOWEST, LOW, NORMAL, HIGH, HIGHEST, MONITOR;}
import org.bukkit.entity.Player; import org.bukkit.event.Listener; import com.gmail.zahusek.tinyprotocolapi.listener.PacketHandler; import com.gmail.zahusek.tinyprotocolapi.listener.PacketListener; import com.gmail.zahusek.tinyprotocolapi.listener.PacketPriority;
package com.gmail.zahusek.test.example; public class ExampleListener implements Listener, PacketListener //implement PakcetListeer { //PacketHandler like EventHandler
// Path: com/gmail/zahusek/tinyprotocolapi/listener/PacketListener.java // public interface PacketListener {} // // Path: com/gmail/zahusek/tinyprotocolapi/listener/PacketPriority.java // public enum PacketPriority // {LOWEST, LOW, NORMAL, HIGH, HIGHEST, MONITOR;} // Path: com/gmail/zahusek/test/example/ExampleListener.java import org.bukkit.entity.Player; import org.bukkit.event.Listener; import com.gmail.zahusek.tinyprotocolapi.listener.PacketHandler; import com.gmail.zahusek.tinyprotocolapi.listener.PacketListener; import com.gmail.zahusek.tinyprotocolapi.listener.PacketPriority; package com.gmail.zahusek.test.example; public class ExampleListener implements Listener, PacketListener //implement PakcetListeer { //PacketHandler like EventHandler
@PacketHandler(priority = PacketPriority.LOW)
google/capillary
lib/src/test/java/com/google/capillary/HybridRsaUtilsTest.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import static org.junit.Assert.assertArrayEquals; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class HybridRsaUtilsTest { /** * Creates a new {@link HybridRsaUtilsTest} instance. */ public HybridRsaUtilsTest() throws GeneralSecurityException { Config.initialize(); } @Test public void testEncryptDecrypt() throws GeneralSecurityException, IOException { PublicKey publicKey = TestUtils.createTestRsaPublicKey(); PrivateKey privateKey = TestUtils.createTestRsaPrivateKey(); // Try Encryption/Decryption for each padding mode.
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/test/java/com/google/capillary/HybridRsaUtilsTest.java import static org.junit.Assert.assertArrayEquals; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class HybridRsaUtilsTest { /** * Creates a new {@link HybridRsaUtilsTest} instance. */ public HybridRsaUtilsTest() throws GeneralSecurityException { Config.initialize(); } @Test public void testEncryptDecrypt() throws GeneralSecurityException, IOException { PublicKey publicKey = TestUtils.createTestRsaPublicKey(); PrivateKey privateKey = TestUtils.createTestRsaPrivateKey(); // Try Encryption/Decryption for each padding mode.
for (Padding padding : Padding.values()) {
google/capillary
lib-android/src/test/java/com/google/capillary/android/DecrypterManagerTest.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.os.Build.VERSION_CODES; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.LinkedList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class DecrypterManagerTest { private static final String PLAINTEXT = "plaintext"; private static final String CIPHERTEXT = "ciphertext"; private static final String PUBLIC_KEY = "public key"; private final Context context = mock(Context.class); private final KeyManager keyManager = mock(KeyManager.class); private final HybridDecrypt hybridDecrypt = mock(HybridDecrypt.class); private final CiphertextStorage ciphertextStorage = mock(CiphertextStorage.class); private final Utils utils = mock(Utils.class); private DecrypterManager decrypterManager; private CapillaryCiphertext.Builder ciphertextBuilder; private CapillaryHandler handler; private Object extra; /** * Creates a new {@link DecrypterManagerTest} instance. */ public DecrypterManagerTest()
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/test/java/com/google/capillary/android/DecrypterManagerTest.java import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.os.Build.VERSION_CODES; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.LinkedList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class DecrypterManagerTest { private static final String PLAINTEXT = "plaintext"; private static final String CIPHERTEXT = "ciphertext"; private static final String PUBLIC_KEY = "public key"; private final Context context = mock(Context.class); private final KeyManager keyManager = mock(KeyManager.class); private final HybridDecrypt hybridDecrypt = mock(HybridDecrypt.class); private final CiphertextStorage ciphertextStorage = mock(CiphertextStorage.class); private final Utils utils = mock(Utils.class); private DecrypterManager decrypterManager; private CapillaryCiphertext.Builder ciphertextBuilder; private CapillaryHandler handler; private Object extra; /** * Creates a new {@link DecrypterManagerTest} instance. */ public DecrypterManagerTest()
throws NoSuchKeyException, GeneralSecurityException, AuthModeUnavailableException {
google/capillary
lib-android/src/test/java/com/google/capillary/android/DecrypterManagerTest.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.os.Build.VERSION_CODES; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.LinkedList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class DecrypterManagerTest { private static final String PLAINTEXT = "plaintext"; private static final String CIPHERTEXT = "ciphertext"; private static final String PUBLIC_KEY = "public key"; private final Context context = mock(Context.class); private final KeyManager keyManager = mock(KeyManager.class); private final HybridDecrypt hybridDecrypt = mock(HybridDecrypt.class); private final CiphertextStorage ciphertextStorage = mock(CiphertextStorage.class); private final Utils utils = mock(Utils.class); private DecrypterManager decrypterManager; private CapillaryCiphertext.Builder ciphertextBuilder; private CapillaryHandler handler; private Object extra; /** * Creates a new {@link DecrypterManagerTest} instance. */ public DecrypterManagerTest()
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/test/java/com/google/capillary/android/DecrypterManagerTest.java import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; import android.content.Context; import android.os.Build.VERSION_CODES; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.LinkedList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class DecrypterManagerTest { private static final String PLAINTEXT = "plaintext"; private static final String CIPHERTEXT = "ciphertext"; private static final String PUBLIC_KEY = "public key"; private final Context context = mock(Context.class); private final KeyManager keyManager = mock(KeyManager.class); private final HybridDecrypt hybridDecrypt = mock(HybridDecrypt.class); private final CiphertextStorage ciphertextStorage = mock(CiphertextStorage.class); private final Utils utils = mock(Utils.class); private DecrypterManager decrypterManager; private CapillaryCiphertext.Builder ciphertextBuilder; private CapillaryHandler handler; private Object extra; /** * Creates a new {@link DecrypterManagerTest} instance. */ public DecrypterManagerTest()
throws NoSuchKeyException, GeneralSecurityException, AuthModeUnavailableException {
google/capillary
lib/src/main/java/com/google/capillary/RsaEcdsaHybridEncrypt.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.PublicKey; import javax.crypto.spec.OAEPParameterSpec;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; /** * A {@link HybridEncrypt} implementation for an authenticated hybrid encryption scheme, which is * called RSA-ECDSA for simplicity, that is based on RSA public-key encryption, AES symmetric key * encryption in GCM mode (AES-GCM), and ECDSA signature algorithm. * * <p>Sample usage: * <pre>{@code * import com.google.capillary.RsaEcdsaConstants.Padding; * import com.google.crypto.tink.HybridDecrypt; * import com.google.crypto.tink.HybridEncrypt; * import com.google.crypto.tink.PublicKeySign; * import com.google.crypto.tink.PublicKeyVerify; * import java.security.PrivateKey; * import java.security.PublicKey; * * // Encryption. * PublicKeySign senderSigner = ...; * PublicKey recipientPublicKey = ...; * HybridEncrypt hybridEncrypt = new RsaEcdsaHybridEncrypt.Builder() * .withSenderSigner(senderSigner) * .withRecipientPublicKey(recipientPublicKey) * .withPadding(Padding.OAEP) * .build(); * byte[] plaintext = ...; * byte[] ciphertext = hybridEncrypt.encrypt(plaintext, null); * * // Decryption. * PublicKeyVerify senderVerifier = ...; * PrivateKey recipientPrivateKey = ...; * HybridDecrypt hybridDecrypt = new RsaEcdsaHybridDecrypt.Builder() * .withSenderVerifier(senderVerifier) * .withRecipientPrivateKey(recipientPrivateKey) * .withPadding(Padding.OAEP) * .build(); * byte[] ciphertext = ...; * byte[] plaintext = hybridDecrypt.decrypt(ciphertext, null); * }</pre> * * <p>The encryption algorithm consists of the following steps: * <ol> * <li>Generate an AES-GCM symmetric key.</li> * <li>Encrypt the AES-GCM key using RSA.</li> * <li>Encrypt the message using the AES-GCM key.</li> * <li>Encode the encrypted AES-GCM key and the encrypted message into a byte array A1.</li> * <li>Sign A1 using ECDSA.</li> * <li>Combine A1 and its signature into a byte array A2.</li> * <li>Output A2 as the RSA-ECDSA ciphertext.</li> * </ol> * * <p>The format of the RsaEcdsa ciphertext is the following: * <pre>{@code * +------------------------------------------+ * | ECDSA Signature Length (4 bytes) | * +------------------------------------------+ * | ECDSA Signature | * +------------------------------------------+ * | RSA+AES-GCM hybrid-encryption ciphertext | * +------------------------------------------+ * }</pre> * * <p>This implementation of RSA-ECDSA depends on the <a href="https://github.com/google/tink" * target="_blank">Tink</a> crypto library to perform AES-GCM and ECDSA operations. */ public final class RsaEcdsaHybridEncrypt implements HybridEncrypt { private final PublicKeySign senderSigner; private final PublicKey recipientPublicKey;
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/main/java/com/google/capillary/RsaEcdsaHybridEncrypt.java import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.PublicKey; import javax.crypto.spec.OAEPParameterSpec; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; /** * A {@link HybridEncrypt} implementation for an authenticated hybrid encryption scheme, which is * called RSA-ECDSA for simplicity, that is based on RSA public-key encryption, AES symmetric key * encryption in GCM mode (AES-GCM), and ECDSA signature algorithm. * * <p>Sample usage: * <pre>{@code * import com.google.capillary.RsaEcdsaConstants.Padding; * import com.google.crypto.tink.HybridDecrypt; * import com.google.crypto.tink.HybridEncrypt; * import com.google.crypto.tink.PublicKeySign; * import com.google.crypto.tink.PublicKeyVerify; * import java.security.PrivateKey; * import java.security.PublicKey; * * // Encryption. * PublicKeySign senderSigner = ...; * PublicKey recipientPublicKey = ...; * HybridEncrypt hybridEncrypt = new RsaEcdsaHybridEncrypt.Builder() * .withSenderSigner(senderSigner) * .withRecipientPublicKey(recipientPublicKey) * .withPadding(Padding.OAEP) * .build(); * byte[] plaintext = ...; * byte[] ciphertext = hybridEncrypt.encrypt(plaintext, null); * * // Decryption. * PublicKeyVerify senderVerifier = ...; * PrivateKey recipientPrivateKey = ...; * HybridDecrypt hybridDecrypt = new RsaEcdsaHybridDecrypt.Builder() * .withSenderVerifier(senderVerifier) * .withRecipientPrivateKey(recipientPrivateKey) * .withPadding(Padding.OAEP) * .build(); * byte[] ciphertext = ...; * byte[] plaintext = hybridDecrypt.decrypt(ciphertext, null); * }</pre> * * <p>The encryption algorithm consists of the following steps: * <ol> * <li>Generate an AES-GCM symmetric key.</li> * <li>Encrypt the AES-GCM key using RSA.</li> * <li>Encrypt the message using the AES-GCM key.</li> * <li>Encode the encrypted AES-GCM key and the encrypted message into a byte array A1.</li> * <li>Sign A1 using ECDSA.</li> * <li>Combine A1 and its signature into a byte array A2.</li> * <li>Output A2 as the RSA-ECDSA ciphertext.</li> * </ol> * * <p>The format of the RsaEcdsa ciphertext is the following: * <pre>{@code * +------------------------------------------+ * | ECDSA Signature Length (4 bytes) | * +------------------------------------------+ * | ECDSA Signature | * +------------------------------------------+ * | RSA+AES-GCM hybrid-encryption ciphertext | * +------------------------------------------+ * }</pre> * * <p>This implementation of RSA-ECDSA depends on the <a href="https://github.com/google/tink" * target="_blank">Tink</a> crypto library to perform AES-GCM and ECDSA operations. */ public final class RsaEcdsaHybridEncrypt implements HybridEncrypt { private final PublicKeySign senderSigner; private final PublicKey recipientPublicKey;
private final Padding padding;
google/capillary
lib/src/test/java/com/google/capillary/RsaEcdsaHybridDecryptTest.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import com.google.crypto.tink.PublicKeyVerify; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Arrays; import org.junit.Test;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaHybridDecryptTest { private final PublicKeySign senderSigner; private final PublicKeyVerify senderVerifier; private final PublicKey recipientPublicKey; private final PrivateKey recipientPrivateKey; /** * Creates a new {@link RsaEcdsaHybridDecryptTest} instance. */ public RsaEcdsaHybridDecryptTest() throws GeneralSecurityException, IOException { Config.initialize(); senderSigner = TestUtils.createTestSenderSigner(); senderVerifier = TestUtils.createTestSenderVerifier(); recipientPublicKey = TestUtils.createTestRsaPublicKey(); recipientPrivateKey = TestUtils.createTestRsaPrivateKey(); } @Test public void testModifyCiphertext() throws GeneralSecurityException { byte[] plaintext = Random.randBytes(20); // Try Encryption/Decryption for each padding mode.
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/test/java/com/google/capillary/RsaEcdsaHybridDecryptTest.java import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import com.google.crypto.tink.PublicKeyVerify; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Arrays; import org.junit.Test; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaHybridDecryptTest { private final PublicKeySign senderSigner; private final PublicKeyVerify senderVerifier; private final PublicKey recipientPublicKey; private final PrivateKey recipientPrivateKey; /** * Creates a new {@link RsaEcdsaHybridDecryptTest} instance. */ public RsaEcdsaHybridDecryptTest() throws GeneralSecurityException, IOException { Config.initialize(); senderSigner = TestUtils.createTestSenderSigner(); senderVerifier = TestUtils.createTestSenderVerifier(); recipientPublicKey = TestUtils.createTestRsaPublicKey(); recipientPrivateKey = TestUtils.createTestRsaPrivateKey(); } @Test public void testModifyCiphertext() throws GeneralSecurityException { byte[] plaintext = Random.randBytes(20); // Try Encryption/Decryption for each padding mode.
for (Padding padding : Padding.values()) {
google/capillary
lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerImplAndroidTest.java
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.Config; import com.google.capillary.NoSuchKeyException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerImplAndroidTest { private static final String KEYCHAIN_ID = "keychain 1"; private Context context; private KeyManager rsaEcdsaKeyManager; private KeyManager webPushKeyManager; /** * Creates a new {@link KeyManagerImplAndroidTest} instance. */ public KeyManagerImplAndroidTest() throws GeneralSecurityException {
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerImplAndroidTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.Config; import com.google.capillary.NoSuchKeyException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerImplAndroidTest { private static final String KEYCHAIN_ID = "keychain 1"; private Context context; private KeyManager rsaEcdsaKeyManager; private KeyManager webPushKeyManager; /** * Creates a new {@link KeyManagerImplAndroidTest} instance. */ public KeyManagerImplAndroidTest() throws GeneralSecurityException {
Config.initialize();
google/capillary
lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerImplAndroidTest.java
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.Config; import com.google.capillary.NoSuchKeyException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore;
IntegrationTest.class.getResourceAsStream("verification_key.dat")) { rsaEcdsaKeyManager = RsaEcdsaKeyManager.getInstance(context, KEYCHAIN_ID, senderVerificationKey); } webPushKeyManager = WebPushKeyManager.getInstance(context, KEYCHAIN_ID); TestUtils.clearKeyStore(); } @Test public void testRsaEcdsaGenerateKeys() throws GeneralSecurityException { testGenerateKeys(rsaEcdsaKeyManager); } @Test public void testWebPushGenerateKeys() throws GeneralSecurityException { testGenerateKeys(webPushKeyManager); } private void testGenerateKeys(KeyManager keyManager) throws GeneralSecurityException { KeyStore keyStore = Utils.getInstance().loadKeyStore(); assertEquals(0, keyStore.size()); keyManager.rawGenerateKeyPair(true); keyManager.rawGenerateKeyPair(false); assertEquals(2, keyStore.size()); } @Test
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerImplAndroidTest.java import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.Config; import com.google.capillary.NoSuchKeyException; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; IntegrationTest.class.getResourceAsStream("verification_key.dat")) { rsaEcdsaKeyManager = RsaEcdsaKeyManager.getInstance(context, KEYCHAIN_ID, senderVerificationKey); } webPushKeyManager = WebPushKeyManager.getInstance(context, KEYCHAIN_ID); TestUtils.clearKeyStore(); } @Test public void testRsaEcdsaGenerateKeys() throws GeneralSecurityException { testGenerateKeys(rsaEcdsaKeyManager); } @Test public void testWebPushGenerateKeys() throws GeneralSecurityException { testGenerateKeys(webPushKeyManager); } private void testGenerateKeys(KeyManager keyManager) throws GeneralSecurityException { KeyStore keyStore = Utils.getInstance().loadKeyStore(); assertEquals(0, keyStore.size()); keyManager.rawGenerateKeyPair(true); keyManager.rawGenerateKeyPair(false); assertEquals(2, keyStore.size()); } @Test
public void testRsaEcdsaGetPublicKey() throws GeneralSecurityException, NoSuchKeyException {
google/capillary
lib-android/src/main/java/com/google/capillary/android/Utils.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // }
import android.app.KeyguardManager; import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import com.google.capillary.AuthModeUnavailableException; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; /** * Provides some useful Android-specific helper functions. */ class Utils { private static final String KEYSTORE_ANDROID = "AndroidKeyStore"; private static Utils instance; private Utils() { } /** * Returns the singleton instance. */ static synchronized Utils getInstance() { if (instance == null) { instance = new Utils(); } return instance; } /** * Creates a storage context that is protected by device-specific credentials. * * <p>This method only has an effect on API levels 24 and above. */ Context getDeviceProtectedStorageContext(Context context) { if (VERSION.SDK_INT >= VERSION_CODES.N) { return context.createDeviceProtectedStorageContext(); } return context; } /** * Checks if the device supports generating authenticated Capillary keys or throws an exception if * it doesn't. */
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // Path: lib-android/src/main/java/com/google/capillary/android/Utils.java import android.app.KeyguardManager; import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import com.google.capillary.AuthModeUnavailableException; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyStore; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; /** * Provides some useful Android-specific helper functions. */ class Utils { private static final String KEYSTORE_ANDROID = "AndroidKeyStore"; private static Utils instance; private Utils() { } /** * Returns the singleton instance. */ static synchronized Utils getInstance() { if (instance == null) { instance = new Utils(); } return instance; } /** * Creates a storage context that is protected by device-specific credentials. * * <p>This method only has an effect on API levels 24 and above. */ Context getDeviceProtectedStorageContext(Context context) { if (VERSION.SDK_INT >= VERSION_CODES.N) { return context.createDeviceProtectedStorageContext(); } return context; } /** * Checks if the device supports generating authenticated Capillary keys or throws an exception if * it doesn't. */
void checkAuthModeIsAvailable(Context context) throws AuthModeUnavailableException {
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // }
import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.demo.server; /** * The implementation of DemoService service. * * <p>See capillary_demo_common.proto for details of the methods. */ final class DemoServiceImpl extends DemoServiceGrpc.DemoServiceImplBase { private static final Logger logger = Logger.getLogger(DemoServiceImpl.class.getName()); private final DemoDb db;
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.demo.server; /** * The implementation of DemoService service. * * <p>See capillary_demo_common.proto for details of the methods. */ final class DemoServiceImpl extends DemoServiceGrpc.DemoServiceImplBase { private static final Logger logger = Logger.getLogger(DemoServiceImpl.class.getName()); private final DemoDb db;
private final EncrypterManager rsaEcdsaEncrypterManager;
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // }
import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger;
responseObserver.onError( Status.INTERNAL.withDescription("unable to add public key").asException()); return; } responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); } @Override public void sendMessage(SendMessageRequest req, StreamObserver<Empty> responseObserver) { logger.info("sendMessage called with:"); logger.info(req.toString()); try { // Get public key. byte[] publicKey = db.getKeyBytes(req.getUserId(), req.getKeyAlgorithm(), req.getIsAuthKey()); // Generate ciphertext. EncrypterManager encrypterManager = getEncrypterManager(req.getKeyAlgorithm()); encrypterManager.loadPublicKey(publicKey); byte[] ciphertext = encrypterManager.encrypt(req.getData().toByteArray()); encrypterManager.clearPublicKey(); String ciphertextString = Base64.encode(ciphertext); // Get FCM token. String token = db.getToken(req.getUserId()); // Create the data map to be sent as a JSON object. Map<String, String> dataMap = new HashMap<>();
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; responseObserver.onError( Status.INTERNAL.withDescription("unable to add public key").asException()); return; } responseObserver.onNext(Empty.getDefaultInstance()); responseObserver.onCompleted(); } @Override public void sendMessage(SendMessageRequest req, StreamObserver<Empty> responseObserver) { logger.info("sendMessage called with:"); logger.info(req.toString()); try { // Get public key. byte[] publicKey = db.getKeyBytes(req.getUserId(), req.getKeyAlgorithm(), req.getIsAuthKey()); // Generate ciphertext. EncrypterManager encrypterManager = getEncrypterManager(req.getKeyAlgorithm()); encrypterManager.loadPublicKey(publicKey); byte[] ciphertext = encrypterManager.encrypt(req.getData().toByteArray()); encrypterManager.clearPublicKey(); String ciphertextString = Base64.encode(ciphertext); // Get FCM token. String token = db.getToken(req.getUserId()); // Create the data map to be sent as a JSON object. Map<String, String> dataMap = new HashMap<>();
dataMap.put(Constants.CAPILLARY_CIPHERTEXT_KEY, ciphertextString);
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // }
import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger;
logger.info("sendMessage called with:"); logger.info(req.toString()); try { // Get public key. byte[] publicKey = db.getKeyBytes(req.getUserId(), req.getKeyAlgorithm(), req.getIsAuthKey()); // Generate ciphertext. EncrypterManager encrypterManager = getEncrypterManager(req.getKeyAlgorithm()); encrypterManager.loadPublicKey(publicKey); byte[] ciphertext = encrypterManager.encrypt(req.getData().toByteArray()); encrypterManager.clearPublicKey(); String ciphertextString = Base64.encode(ciphertext); // Get FCM token. String token = db.getToken(req.getUserId()); // Create the data map to be sent as a JSON object. Map<String, String> dataMap = new HashMap<>(); dataMap.put(Constants.CAPILLARY_CIPHERTEXT_KEY, ciphertextString); dataMap.put(Constants.CAPILLARY_KEY_ALGORITHM_KEY, req.getKeyAlgorithm().name()); // Send the data map after the requested delay. executorService.schedule(() -> { try { fcmSender.sendDataMessage(token, dataMap); } catch (IOException e) { e.printStackTrace(); } }, req.getDelaySeconds(), TimeUnit.SECONDS);
// Path: lib/src/main/java/com/google/capillary/EncrypterManager.java // public abstract class EncrypterManager { // // private boolean isLoaded; // private CapillaryPublicKey capillaryPublicKey; // private HybridEncrypt encrypter; // // /** // * Loads a serialized Capillary public key. // * // * @param publicKey the serialized Capillary public key. // * @throws GeneralSecurityException if the given Capillary public key cannot be loaded. // */ // public synchronized void loadPublicKey(byte[] publicKey) throws GeneralSecurityException { // try { // capillaryPublicKey = CapillaryPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // encrypter = rawLoadPublicKey(capillaryPublicKey.getKeyBytes().toByteArray()); // isLoaded = true; // } // // /** // * Creates a {@link HybridEncrypt} for a raw public key embedded in a Capillary public key. // */ // abstract HybridEncrypt rawLoadPublicKey(byte[] rawPublicKey) throws GeneralSecurityException; // // /** // * Encryptes the given plaintext into a Capillary ciphertext. // * // * @param data the plaintext. // * @return the Capillary ciphertext. // * @throws GeneralSecurityException if the encryption fails. // */ // public synchronized byte[] encrypt(byte[] data) throws GeneralSecurityException { // if (!isLoaded) { // throw new GeneralSecurityException("public key is not loaded"); // } // byte[] ciphertext = encrypter.encrypt(data, null); // return CapillaryCiphertext.newBuilder() // .setKeychainUniqueId(capillaryPublicKey.getKeychainUniqueId()) // .setKeySerialNumber((capillaryPublicKey.getSerialNumber())) // .setIsAuthKey(capillaryPublicKey.getIsAuth()) // .setCiphertext(ByteString.copyFrom(ciphertext)) // .build().toByteArray(); // } // // /** // * Clears the loaded Capillary public key. // */ // public synchronized void clearPublicKey() { // isLoaded = false; // capillaryPublicKey = null; // encrypter = null; // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: demo/common/src/main/java/com/google/capillary/demo/common/Constants.java // public class Constants { // // public static final String CAPILLARY_CIPHERTEXT_KEY = "capillary_ciphertext"; // public static final String CAPILLARY_KEY_ALGORITHM_KEY = "capillary_key_algorithm"; // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServiceImpl.java import com.google.capillary.EncrypterManager; import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.Constants; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SendMessageRequest; import com.google.crypto.tink.subtle.Base64; import com.google.protobuf.Empty; import io.grpc.Status; import io.grpc.stub.StreamObserver; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; logger.info("sendMessage called with:"); logger.info(req.toString()); try { // Get public key. byte[] publicKey = db.getKeyBytes(req.getUserId(), req.getKeyAlgorithm(), req.getIsAuthKey()); // Generate ciphertext. EncrypterManager encrypterManager = getEncrypterManager(req.getKeyAlgorithm()); encrypterManager.loadPublicKey(publicKey); byte[] ciphertext = encrypterManager.encrypt(req.getData().toByteArray()); encrypterManager.clearPublicKey(); String ciphertextString = Base64.encode(ciphertext); // Get FCM token. String token = db.getToken(req.getUserId()); // Create the data map to be sent as a JSON object. Map<String, String> dataMap = new HashMap<>(); dataMap.put(Constants.CAPILLARY_CIPHERTEXT_KEY, ciphertextString); dataMap.put(Constants.CAPILLARY_KEY_ALGORITHM_KEY, req.getKeyAlgorithm().name()); // Send the data map after the requested delay. executorService.schedule(() -> { try { fcmSender.sendDataMessage(token, dataMap); } catch (IOException e) { e.printStackTrace(); } }, req.getDelaySeconds(), TimeUnit.SECONDS);
} catch (NoSuchUserException | NoSuchKeyException e) {
google/capillary
demo/android/src/main/java/com/google/capillary/demo/android/DemoCapillaryHandler.java
// Path: lib-android/src/main/java/com/google/capillary/android/CapillaryHandler.java // public interface CapillaryHandler { // // /** // * Provides the plaintext after decrypting a Capillary ciphertext. // * // * @param isAuthKey whether the decryption was done using a public key requiring authentication. // * @param data the plaintext. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void handleData(boolean isAuthKey, byte[] data, Object extra); // // /** // * Provides the generated Capillary public key. // * // * @param isAuthKey whether the public key requires authentication. // * @param publicKey the public key. // * @param extra the extra parameter originally passed to {@link KeyManager}. // */ // void handlePublicKey(boolean isAuthKey, byte[] publicKey, Object extra); // // /** // * Provides the Capillary public key that was generated as a result of a decryption error. // * // * @param isAuthKey whether the public key requires authentication. // * @param publicKey the public key. // * @param ciphertext the ciphertext that caused the decryption error. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void handlePublicKey(boolean isAuthKey, byte[] publicKey, byte[] ciphertext, Object extra); // // /** // * Signals that a Capillary ciphertext was saved to be decrypted after user authentication. // * // * @param ciphertext the saved Capillary ciphertext. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void authCiphertextSavedForLater(byte[] ciphertext, Object extra); // // /** // * Signals that an error has occurred. // * // * @param errorCode the error code enum. // * @param ciphertext the Capillary ciphertext that is affected by this error. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void error(CapillaryHandlerErrorCode errorCode, byte[] ciphertext, Object extra); // } // // Path: lib-android/src/main/java/com/google/capillary/android/CapillaryHandlerErrorCode.java // public enum CapillaryHandlerErrorCode { // // A ciphertext that was encrypted using an authenticated Capillary public key was received in a // // device that does not have authentication enabled. // AUTH_CIPHER_IN_NO_AUTH_DEVICE, // // A malformed ciphertext was received. // MALFORMED_CIPHERTEXT, // // A ciphertext that was encrypted using an older Capillary public key was received. The client // // should re-register the current Capillary public key with the application server to avoid // // this error happening again. // STALE_CIPHERTEXT, // // An error other than the above has occurred. // UNKNOWN_ERROR // }
import android.content.Context; import android.util.Log; import com.google.capillary.android.CapillaryHandler; import com.google.capillary.android.CapillaryHandlerErrorCode; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.DemoServiceGrpc.DemoServiceBlockingStub; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SecureNotification; import com.google.capillary.demo.common.SendMessageRequest; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import io.grpc.ManagedChannel;
* This Capillary public key was generated due to a failure in decrypting a Capillary ciphertext. * Therefore, this method first registers the new Capillary public key with the application * server, and then requests the Capillary ciphertext to be resend. */ @Override public void handlePublicKey( boolean isAuthKey, byte[] publicKey, byte[] ciphertext, Object extra) { handlePublicKey(isAuthKey, publicKey, extra); KeyAlgorithm keyAlgorithm = (KeyAlgorithm) extra; SendMessageRequest request = SendMessageRequest.newBuilder() .setUserId(Utils.getUserId(context)) .setKeyAlgorithm(keyAlgorithm) .setIsAuthKey(isAuthKey) .setData(Utils.createSecureMessageBytes("retry msg", keyAlgorithm, isAuthKey)).build(); blockingStub.sendMessage(request); } /** * This indicates that a Capillary ciphertext was saved to be decrypted later. */ @Override public void authCiphertextSavedForLater(byte[] ciphertext, Object extra) { KeyAlgorithm keyAlgorithm = (KeyAlgorithm) extra; Log.d(TAG, String.format("ciphertext saved: KeyAlgorithm=%s", keyAlgorithm)); } /** * This indicates an error. */ @Override
// Path: lib-android/src/main/java/com/google/capillary/android/CapillaryHandler.java // public interface CapillaryHandler { // // /** // * Provides the plaintext after decrypting a Capillary ciphertext. // * // * @param isAuthKey whether the decryption was done using a public key requiring authentication. // * @param data the plaintext. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void handleData(boolean isAuthKey, byte[] data, Object extra); // // /** // * Provides the generated Capillary public key. // * // * @param isAuthKey whether the public key requires authentication. // * @param publicKey the public key. // * @param extra the extra parameter originally passed to {@link KeyManager}. // */ // void handlePublicKey(boolean isAuthKey, byte[] publicKey, Object extra); // // /** // * Provides the Capillary public key that was generated as a result of a decryption error. // * // * @param isAuthKey whether the public key requires authentication. // * @param publicKey the public key. // * @param ciphertext the ciphertext that caused the decryption error. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void handlePublicKey(boolean isAuthKey, byte[] publicKey, byte[] ciphertext, Object extra); // // /** // * Signals that a Capillary ciphertext was saved to be decrypted after user authentication. // * // * @param ciphertext the saved Capillary ciphertext. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void authCiphertextSavedForLater(byte[] ciphertext, Object extra); // // /** // * Signals that an error has occurred. // * // * @param errorCode the error code enum. // * @param ciphertext the Capillary ciphertext that is affected by this error. // * @param extra the extra parameter originally passed to {@link DecrypterManager}. // */ // void error(CapillaryHandlerErrorCode errorCode, byte[] ciphertext, Object extra); // } // // Path: lib-android/src/main/java/com/google/capillary/android/CapillaryHandlerErrorCode.java // public enum CapillaryHandlerErrorCode { // // A ciphertext that was encrypted using an authenticated Capillary public key was received in a // // device that does not have authentication enabled. // AUTH_CIPHER_IN_NO_AUTH_DEVICE, // // A malformed ciphertext was received. // MALFORMED_CIPHERTEXT, // // A ciphertext that was encrypted using an older Capillary public key was received. The client // // should re-register the current Capillary public key with the application server to avoid // // this error happening again. // STALE_CIPHERTEXT, // // An error other than the above has occurred. // UNKNOWN_ERROR // } // Path: demo/android/src/main/java/com/google/capillary/demo/android/DemoCapillaryHandler.java import android.content.Context; import android.util.Log; import com.google.capillary.android.CapillaryHandler; import com.google.capillary.android.CapillaryHandlerErrorCode; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.DemoServiceGrpc; import com.google.capillary.demo.common.DemoServiceGrpc.DemoServiceBlockingStub; import com.google.capillary.demo.common.KeyAlgorithm; import com.google.capillary.demo.common.SecureNotification; import com.google.capillary.demo.common.SendMessageRequest; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import io.grpc.ManagedChannel; * This Capillary public key was generated due to a failure in decrypting a Capillary ciphertext. * Therefore, this method first registers the new Capillary public key with the application * server, and then requests the Capillary ciphertext to be resend. */ @Override public void handlePublicKey( boolean isAuthKey, byte[] publicKey, byte[] ciphertext, Object extra) { handlePublicKey(isAuthKey, publicKey, extra); KeyAlgorithm keyAlgorithm = (KeyAlgorithm) extra; SendMessageRequest request = SendMessageRequest.newBuilder() .setUserId(Utils.getUserId(context)) .setKeyAlgorithm(keyAlgorithm) .setIsAuthKey(isAuthKey) .setData(Utils.createSecureMessageBytes("retry msg", keyAlgorithm, isAuthKey)).build(); blockingStub.sendMessage(request); } /** * This indicates that a Capillary ciphertext was saved to be decrypted later. */ @Override public void authCiphertextSavedForLater(byte[] ciphertext, Object extra) { KeyAlgorithm keyAlgorithm = (KeyAlgorithm) extra; Log.d(TAG, String.format("ciphertext saved: KeyAlgorithm=%s", keyAlgorithm)); } /** * This indicates an error. */ @Override
public void error(CapillaryHandlerErrorCode errorCode, byte[] ciphertext, Object extra) {
google/capillary
lib-android/src/androidTest/java/com/google/capillary/android/AndroidKeyStoreRsaUtilsAndroidTest.java
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import java.security.UnrecoverableKeyException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.NoSuchKeyException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException;
@Test public void testGenerateKeyPair() throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { String keychainId1 = KEYCHAIN_ID; final String keychainId2 = "keychain 2"; assertEquals(0, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId1, false); assertEquals(1, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId1, true); assertEquals(2, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId2, false); assertEquals(3, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId2, true); assertEquals(4, keyStore.size()); } @Test public void testGetPublicKey() throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException,
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/androidTest/java/com/google/capillary/android/AndroidKeyStoreRsaUtilsAndroidTest.java import java.security.UnrecoverableKeyException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.NoSuchKeyException; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; @Test public void testGenerateKeyPair() throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException { String keychainId1 = KEYCHAIN_ID; final String keychainId2 = "keychain 2"; assertEquals(0, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId1, false); assertEquals(1, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId1, true); assertEquals(2, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId2, false); assertEquals(3, keyStore.size()); AndroidKeyStoreRsaUtils.generateKeyPair(context, keychainId2, true); assertEquals(4, keyStore.size()); } @Test public void testGetPublicKey() throws KeyStoreException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException,
NoSuchKeyException {
google/capillary
lib/src/main/java/com/google/capillary/HybridRsaUtils.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.capillary.internal.HybridRsaCiphertext; import com.google.crypto.tink.Aead; import com.google.crypto.tink.BinaryKeysetReader; import com.google.crypto.tink.BinaryKeysetWriter; import com.google.crypto.tink.CleartextKeysetHandle; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.aead.AeadFactory; import com.google.crypto.tink.aead.AeadKeyTemplates; import com.google.crypto.tink.proto.KeyTemplate; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.Cipher; import javax.crypto.spec.OAEPParameterSpec;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; public final class HybridRsaUtils { private static final KeyTemplate SYMMETRIC_KEY_TEMPLATE = AeadKeyTemplates.AES128_GCM; private static final byte[] emptyEad = new byte[0]; /** * Encrypts the given plaintext using RSA hybrid encryption. * * @param plaintext the plaintext to encrypt. * @param publicKey the RSA public key. * @param padding the RSA padding to use. * @param oaepParams the {@link OAEPParameterSpec} to use for OAEP padding. * @return the ciphertext. * @throws GeneralSecurityException if encryption fails. */ public static byte[] encrypt(
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/main/java/com/google/capillary/HybridRsaUtils.java import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.capillary.internal.HybridRsaCiphertext; import com.google.crypto.tink.Aead; import com.google.crypto.tink.BinaryKeysetReader; import com.google.crypto.tink.BinaryKeysetWriter; import com.google.crypto.tink.CleartextKeysetHandle; import com.google.crypto.tink.KeysetHandle; import com.google.crypto.tink.aead.AeadFactory; import com.google.crypto.tink.aead.AeadKeyTemplates; import com.google.crypto.tink.proto.KeyTemplate; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.Cipher; import javax.crypto.spec.OAEPParameterSpec; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; public final class HybridRsaUtils { private static final KeyTemplate SYMMETRIC_KEY_TEMPLATE = AeadKeyTemplates.AES128_GCM; private static final byte[] emptyEad = new byte[0]; /** * Encrypts the given plaintext using RSA hybrid encryption. * * @param plaintext the plaintext to encrypt. * @param publicKey the RSA public key. * @param padding the RSA padding to use. * @param oaepParams the {@link OAEPParameterSpec} to use for OAEP padding. * @return the ciphertext. * @throws GeneralSecurityException if encryption fails. */ public static byte[] encrypt(
byte[] plaintext, PublicKey publicKey, Padding padding, OAEPParameterSpec oaepParams)
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoDb.java
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.KeyAlgorithm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;
private final String databasePath; /** * Initializes a new {@link DemoDb}. */ DemoDb(String databasePath) { this.databasePath = databasePath; } /** * Inserts or updates the given recipient Capillary public key in the SQLite database. */ void addOrUpdatePublicKey(AddOrUpdatePublicKeyRequest request) throws SQLException { try ( Connection connection = DriverManager.getConnection(databasePath); PreparedStatement statement = connection.prepareStatement(CMD_PUT_PUBLIC_KEY) ) { statement.setString(1, request.getUserId()); statement.setInt(2, request.getAlgorithmValue()); statement.setInt(3, request.getIsAuth() ? 1 : 0); statement.setBytes(4, request.getKeyBytes().toByteArray()); statement.executeUpdate(); } } /** * Returns the Capillary public key of the given user and key parameters. */ byte[] getKeyBytes(String userId, KeyAlgorithm algorithm, boolean isAuth)
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoDb.java import com.google.capillary.NoSuchKeyException; import com.google.capillary.demo.common.AddOrUpdatePublicKeyRequest; import com.google.capillary.demo.common.AddOrUpdateUserRequest; import com.google.capillary.demo.common.KeyAlgorithm; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; private final String databasePath; /** * Initializes a new {@link DemoDb}. */ DemoDb(String databasePath) { this.databasePath = databasePath; } /** * Inserts or updates the given recipient Capillary public key in the SQLite database. */ void addOrUpdatePublicKey(AddOrUpdatePublicKeyRequest request) throws SQLException { try ( Connection connection = DriverManager.getConnection(databasePath); PreparedStatement statement = connection.prepareStatement(CMD_PUT_PUBLIC_KEY) ) { statement.setString(1, request.getUserId()); statement.setInt(2, request.getAlgorithmValue()); statement.setInt(3, request.getIsAuth() ? 1 : 0); statement.setBytes(4, request.getKeyBytes().toByteArray()); statement.executeUpdate(); } } /** * Returns the Capillary public key of the given user and key parameters. */ byte[] getKeyBytes(String userId, KeyAlgorithm algorithm, boolean isAuth)
throws SQLException, NoSuchKeyException {
google/capillary
lib-android/src/test/java/com/google/capillary/android/KeyManagerTest.java
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import android.content.Context; import com.google.capillary.NoSuchKeyException; import com.google.crypto.tink.HybridDecrypt; import java.security.GeneralSecurityException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class KeyManagerTest { @Test public void testStorageContextIsPrivate() { Context context = mock(Context.class); new KeyManager(context, Utils.getInstance(), "keychain id") { @Override void rawGenerateKeyPair(boolean isAuth) throws GeneralSecurityException { } @Override
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/test/java/com/google/capillary/android/KeyManagerTest.java import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import android.content.Context; import com.google.capillary.NoSuchKeyException; import com.google.crypto.tink.HybridDecrypt; import java.security.GeneralSecurityException; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(JUnit4.class) public final class KeyManagerTest { @Test public void testStorageContextIsPrivate() { Context context = mock(Context.class); new KeyManager(context, Utils.getInstance(), "keychain id") { @Override void rawGenerateKeyPair(boolean isAuth) throws GeneralSecurityException { } @Override
byte[] rawGetPublicKey(boolean isAuth) throws NoSuchKeyException, GeneralSecurityException {
google/capillary
lib/src/test/java/com/google/capillary/RsaEcdsaEncrypterManagerTest.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.capillary.internal.WrappedRsaEcdsaPublicKey; import com.google.protobuf.ByteString; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaEncrypterManagerTest { private RsaEcdsaEncrypterManager encrypterManager; /** * Creates a new {@link RsaEcdsaEncrypterManagerTest} instance. */ public RsaEcdsaEncrypterManagerTest() throws GeneralSecurityException { Config.initialize(); } /** * Initializes test case-specific state. */ @Before public void setUp() throws IOException, GeneralSecurityException { try (InputStream senderSigner = RsaEcdsaEncrypterManagerTest.class.getResourceAsStream("signing_key.dat")) { encrypterManager = new RsaEcdsaEncrypterManager(senderSigner); } } @Test public void testLoadMalformedRawPublicKey() { byte[] rawPublicKey = "malformed raw public key".getBytes(); try { encrypterManager.rawLoadPublicKey(rawPublicKey); fail("Did not throw GeneralSecurityException"); } catch (GeneralSecurityException e) { // This is expected. } } @Test public void testLoadValidRawPublicKey() throws IOException, GeneralSecurityException { byte[] testRsaPublicKey = TestUtils.getBytes("rsa_public_key.dat"); byte[] rawPublicKey = WrappedRsaEcdsaPublicKey.newBuilder()
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/test/java/com/google/capillary/RsaEcdsaEncrypterManagerTest.java import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.capillary.internal.WrappedRsaEcdsaPublicKey; import com.google.protobuf.ByteString; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaEncrypterManagerTest { private RsaEcdsaEncrypterManager encrypterManager; /** * Creates a new {@link RsaEcdsaEncrypterManagerTest} instance. */ public RsaEcdsaEncrypterManagerTest() throws GeneralSecurityException { Config.initialize(); } /** * Initializes test case-specific state. */ @Before public void setUp() throws IOException, GeneralSecurityException { try (InputStream senderSigner = RsaEcdsaEncrypterManagerTest.class.getResourceAsStream("signing_key.dat")) { encrypterManager = new RsaEcdsaEncrypterManager(senderSigner); } } @Test public void testLoadMalformedRawPublicKey() { byte[] rawPublicKey = "malformed raw public key".getBytes(); try { encrypterManager.rawLoadPublicKey(rawPublicKey); fail("Did not throw GeneralSecurityException"); } catch (GeneralSecurityException e) { // This is expected. } } @Test public void testLoadValidRawPublicKey() throws IOException, GeneralSecurityException { byte[] testRsaPublicKey = TestUtils.getBytes("rsa_public_key.dat"); byte[] rawPublicKey = WrappedRsaEcdsaPublicKey.newBuilder()
.setPadding(Padding.OAEP.name())
google/capillary
lib/src/main/java/com/google/capillary/RsaEcdsaHybridDecrypt.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.PublicKeyVerify; import com.google.protobuf.InvalidProtocolBufferException; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.PrivateKey; import javax.crypto.spec.OAEPParameterSpec;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; /** * A {@link HybridDecrypt} implementation for an authenticated hybrid encryption scheme, which is * called RSA-ECDSA for simplicity, that is based on RSA public-key encryption, AES symmetric key * encryption in GCM mode (AES-GCM), and ECDSA signature algorithm. * * <p>Sample usage: * <pre>{@code * import com.google.capillary.RsaEcdsaConstants.Padding; * import com.google.crypto.tink.HybridDecrypt; * import com.google.crypto.tink.HybridEncrypt; * import com.google.crypto.tink.PublicKeySign; * import com.google.crypto.tink.PublicKeyVerify; * import java.security.PrivateKey; * import java.security.PublicKey; * * // Encryption. * PublicKeySign senderSigner = ...; * PublicKey recipientPublicKey = ...; * HybridEncrypt hybridEncrypt = new RsaEcdsaHybridEncrypt.Builder() * .withSenderSigner(senderSigner) * .withRecipientPublicKey(recipientPublicKey) * .withPadding(Padding.OAEP) * .build(); * byte[] plaintext = ...; * byte[] ciphertext = hybridEncrypt.encrypt(plaintext, null); * * // Decryption. * PublicKeyVerify senderVerifier = ...; * PrivateKey recipientPrivateKey = ...; * HybridDecrypt hybridDecrypt = new RsaEcdsaHybridDecrypt.Builder() * .withSenderVerifier(senderVerifier) * .withRecipientPrivateKey(recipientPrivateKey) * .withPadding(Padding.OAEP) * .build(); * byte[] ciphertext = ...; * byte[] plaintext = hybridDecrypt.decrypt(ciphertext, null); * }</pre> * * <p>The decryption algorithm consists of the following steps: * <ol> * <li>Parse the ciphertext bytes into a signed byte array B1 and a signature.</li> * <li>Verify that the signature validates for B1. If not, abort.</li> * <li>Parse B1 into an encrypted AES-GCM key B2 and an encrypted message B3.</li> * <li>Decrypt B2 using RSA algorithm to obtain a AES-GCM key K1.</li> * <li>Decrypt B3 using K1 to obtain the plaintext.</li> * <li>Output the plaintext.</li> * </ol> * * <p>The format of the RsaEcdsa ciphertext is the following: * <pre>{@code * +------------------------------------------+ * | ECDSA Signature Length (4 bytes) | * +------------------------------------------+ * | ECDSA Signature | * +------------------------------------------+ * | RSA+AES-GCM hybrid-encryption ciphertext | * +------------------------------------------+ * }</pre> * * <p>This implementation of RSA-ECDSA depends on the <a href="https://github.com/google/tink" * target="_blank">Tink</a> crypto library to perform AES-GCM and ECDSA operations. */ public final class RsaEcdsaHybridDecrypt implements HybridDecrypt { private final PublicKeyVerify senderVerifier; private final PrivateKey recipientPrivateKey;
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/main/java/com/google/capillary/RsaEcdsaHybridDecrypt.java import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.PublicKeyVerify; import com.google.protobuf.InvalidProtocolBufferException; import java.io.IOException; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.PrivateKey; import javax.crypto.spec.OAEPParameterSpec; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; /** * A {@link HybridDecrypt} implementation for an authenticated hybrid encryption scheme, which is * called RSA-ECDSA for simplicity, that is based on RSA public-key encryption, AES symmetric key * encryption in GCM mode (AES-GCM), and ECDSA signature algorithm. * * <p>Sample usage: * <pre>{@code * import com.google.capillary.RsaEcdsaConstants.Padding; * import com.google.crypto.tink.HybridDecrypt; * import com.google.crypto.tink.HybridEncrypt; * import com.google.crypto.tink.PublicKeySign; * import com.google.crypto.tink.PublicKeyVerify; * import java.security.PrivateKey; * import java.security.PublicKey; * * // Encryption. * PublicKeySign senderSigner = ...; * PublicKey recipientPublicKey = ...; * HybridEncrypt hybridEncrypt = new RsaEcdsaHybridEncrypt.Builder() * .withSenderSigner(senderSigner) * .withRecipientPublicKey(recipientPublicKey) * .withPadding(Padding.OAEP) * .build(); * byte[] plaintext = ...; * byte[] ciphertext = hybridEncrypt.encrypt(plaintext, null); * * // Decryption. * PublicKeyVerify senderVerifier = ...; * PrivateKey recipientPrivateKey = ...; * HybridDecrypt hybridDecrypt = new RsaEcdsaHybridDecrypt.Builder() * .withSenderVerifier(senderVerifier) * .withRecipientPrivateKey(recipientPrivateKey) * .withPadding(Padding.OAEP) * .build(); * byte[] ciphertext = ...; * byte[] plaintext = hybridDecrypt.decrypt(ciphertext, null); * }</pre> * * <p>The decryption algorithm consists of the following steps: * <ol> * <li>Parse the ciphertext bytes into a signed byte array B1 and a signature.</li> * <li>Verify that the signature validates for B1. If not, abort.</li> * <li>Parse B1 into an encrypted AES-GCM key B2 and an encrypted message B3.</li> * <li>Decrypt B2 using RSA algorithm to obtain a AES-GCM key K1.</li> * <li>Decrypt B3 using K1 to obtain the plaintext.</li> * <li>Output the plaintext.</li> * </ol> * * <p>The format of the RsaEcdsa ciphertext is the following: * <pre>{@code * +------------------------------------------+ * | ECDSA Signature Length (4 bytes) | * +------------------------------------------+ * | ECDSA Signature | * +------------------------------------------+ * | RSA+AES-GCM hybrid-encryption ciphertext | * +------------------------------------------+ * }</pre> * * <p>This implementation of RSA-ECDSA depends on the <a href="https://github.com/google/tink" * target="_blank">Tink</a> crypto library to perform AES-GCM and ECDSA operations. */ public final class RsaEcdsaHybridDecrypt implements HybridDecrypt { private final PublicKeyVerify senderVerifier; private final PrivateKey recipientPrivateKey;
private final Padding padding;
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // }
import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.demo.server; /** * The starting point of the demo app server. */ public final class DemoServer { private static final Logger logger = Logger.getLogger(DemoServer.class.getName()); private static final String PORT_OPTION = "port"; private static final String DATABASE_PATH_OPTION = "database_path"; private static final String ECDSA_PRIVATE_KEY_PATH_OPTION = "ecdsa_private_key_path"; private static final String TLS_CERT_PATH_OPTION = "tls_cert_path"; private static final String TLS_PRIVATE_KEY_PATH_OPTION = "tls_private_key_path"; private static final String SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION = "service_account_credentials_path"; private static final String FIREBASE_PROJECT_ID_OPTION = "firebase_project_id"; private Server server; /** * Launches the server. * * @param args the command line args. * @throws Exception as a catch-all exception in main method. */ public static void main(String[] args) throws Exception { // Initialize the Capillary library.
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.demo.server; /** * The starting point of the demo app server. */ public final class DemoServer { private static final Logger logger = Logger.getLogger(DemoServer.class.getName()); private static final String PORT_OPTION = "port"; private static final String DATABASE_PATH_OPTION = "database_path"; private static final String ECDSA_PRIVATE_KEY_PATH_OPTION = "ecdsa_private_key_path"; private static final String TLS_CERT_PATH_OPTION = "tls_cert_path"; private static final String TLS_PRIVATE_KEY_PATH_OPTION = "tls_private_key_path"; private static final String SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION = "service_account_credentials_path"; private static final String FIREBASE_PROJECT_ID_OPTION = "firebase_project_id"; private Server server; /** * Launches the server. * * @param args the command line args. * @throws Exception as a catch-all exception in main method. */ public static void main(String[] args) throws Exception { // Initialize the Capillary library.
Config.initialize();
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // }
import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser;
.required() .build(); Option databasePath = Option.builder() .longOpt(DATABASE_PATH_OPTION) .desc("The path to sqlite database.") .hasArg() .required() .build(); Options options = new Options(); options.addOption(port); options.addOption(firebaseProjectId); options.addOption(serviceAccountCredentialsPath); options.addOption(ecdsaPrivateKeyPath); options.addOption(tlsPrivateKeyPath); options.addOption(tlsCertPath); options.addOption(databasePath); CommandLineParser cmdLineParser = new DefaultParser(); return cmdLineParser.parse(options, commandLineArguments); } private void start(CommandLine cmd) throws IOException, GeneralSecurityException, SQLException { // The port on which the server should run. int port = Integer.valueOf(cmd.getOptionValue(PORT_OPTION)); // The FCM message sender. FcmSender fcmSender = new FcmSender( cmd.getOptionValue(FIREBASE_PROJECT_ID_OPTION), cmd.getOptionValue(SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION)); // The Capillary encrypter managers.
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; .required() .build(); Option databasePath = Option.builder() .longOpt(DATABASE_PATH_OPTION) .desc("The path to sqlite database.") .hasArg() .required() .build(); Options options = new Options(); options.addOption(port); options.addOption(firebaseProjectId); options.addOption(serviceAccountCredentialsPath); options.addOption(ecdsaPrivateKeyPath); options.addOption(tlsPrivateKeyPath); options.addOption(tlsCertPath); options.addOption(databasePath); CommandLineParser cmdLineParser = new DefaultParser(); return cmdLineParser.parse(options, commandLineArguments); } private void start(CommandLine cmd) throws IOException, GeneralSecurityException, SQLException { // The port on which the server should run. int port = Integer.valueOf(cmd.getOptionValue(PORT_OPTION)); // The FCM message sender. FcmSender fcmSender = new FcmSender( cmd.getOptionValue(FIREBASE_PROJECT_ID_OPTION), cmd.getOptionValue(SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION)); // The Capillary encrypter managers.
RsaEcdsaEncrypterManager rsaEcdsaEncrypterManager;
google/capillary
demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // }
import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser;
.hasArg() .required() .build(); Options options = new Options(); options.addOption(port); options.addOption(firebaseProjectId); options.addOption(serviceAccountCredentialsPath); options.addOption(ecdsaPrivateKeyPath); options.addOption(tlsPrivateKeyPath); options.addOption(tlsCertPath); options.addOption(databasePath); CommandLineParser cmdLineParser = new DefaultParser(); return cmdLineParser.parse(options, commandLineArguments); } private void start(CommandLine cmd) throws IOException, GeneralSecurityException, SQLException { // The port on which the server should run. int port = Integer.valueOf(cmd.getOptionValue(PORT_OPTION)); // The FCM message sender. FcmSender fcmSender = new FcmSender( cmd.getOptionValue(FIREBASE_PROJECT_ID_OPTION), cmd.getOptionValue(SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION)); // The Capillary encrypter managers. RsaEcdsaEncrypterManager rsaEcdsaEncrypterManager; try (FileInputStream senderSigningKey = new FileInputStream(cmd.getOptionValue(ECDSA_PRIVATE_KEY_PATH_OPTION))) { rsaEcdsaEncrypterManager = new RsaEcdsaEncrypterManager(senderSigningKey); }
// Path: lib/src/main/java/com/google/capillary/Config.java // public final class Config { // // /** // * Initializes the Capillary library. // * // * <p>This should be called before using any functionality provided by Capillary. // * // * @throws GeneralSecurityException if the initialization fails. // */ // public static void initialize() throws GeneralSecurityException { // com.google.crypto.tink.Config.register(SignatureConfig.TINK_1_1_0); // com.google.crypto.tink.Config.register(AeadConfig.TINK_1_1_0); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaEncrypterManager.java // public final class RsaEcdsaEncrypterManager extends EncrypterManager { // // private final PublicKeySign senderSigner; // // /** // * Constructs a new RSA-ECDSA EncrypterManager. // * // * <p>Please note that the {@link InputStream} {@code senderSigningKey} will not be closed. // * // * @param senderSigningKey the serialized Tink signing key. // * @throws GeneralSecurityException if the initialization fails. // * @throws IOException if the given sender signing key cannot be read. // */ // public RsaEcdsaEncrypterManager(InputStream senderSigningKey) // throws GeneralSecurityException, IOException { // KeysetHandle signingKeyHandle = CleartextKeysetHandle // .read(BinaryKeysetReader.withInputStream(senderSigningKey)); // senderSigner = PublicKeySignFactory.getPrimitive(signingKeyHandle); // } // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedRsaEcdsaPublicKey wrappedRsaEcdsaPublicKey; // try { // wrappedRsaEcdsaPublicKey = WrappedRsaEcdsaPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // PublicKey recipientPublicKey = KeyFactory.getInstance("RSA").generatePublic( // new X509EncodedKeySpec(wrappedRsaEcdsaPublicKey.getKeyBytes().toByteArray())); // return new RsaEcdsaHybridEncrypt.Builder() // .withSenderSigner(senderSigner) // .withRecipientPublicKey(recipientPublicKey) // .withPadding(RsaEcdsaConstants.Padding.valueOf(wrappedRsaEcdsaPublicKey.getPadding())) // .build(); // } // } // // Path: lib/src/main/java/com/google/capillary/WebPushEncrypterManager.java // public final class WebPushEncrypterManager extends EncrypterManager { // // @Override // HybridEncrypt rawLoadPublicKey(byte[] publicKey) throws GeneralSecurityException { // WrappedWebPushPublicKey wrappedWebPushPublicKey; // try { // wrappedWebPushPublicKey = WrappedWebPushPublicKey.parseFrom(publicKey); // } catch (InvalidProtocolBufferException e) { // throw new GeneralSecurityException("unable to parse public key", e); // } // return new WebPushHybridEncrypt.Builder() // .withAuthSecret(wrappedWebPushPublicKey.getAuthSecret().toByteArray()) // .withRecipientPublicKey(wrappedWebPushPublicKey.getKeyBytes().toByteArray()) // .build(); // } // } // Path: demo/server/src/main/java/com/google/capillary/demo/server/DemoServer.java import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import com.google.capillary.Config; import com.google.capillary.RsaEcdsaEncrypterManager; import com.google.capillary.WebPushEncrypterManager; import io.grpc.BindableService; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; import java.sql.SQLException; import java.util.logging.Logger; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; .hasArg() .required() .build(); Options options = new Options(); options.addOption(port); options.addOption(firebaseProjectId); options.addOption(serviceAccountCredentialsPath); options.addOption(ecdsaPrivateKeyPath); options.addOption(tlsPrivateKeyPath); options.addOption(tlsCertPath); options.addOption(databasePath); CommandLineParser cmdLineParser = new DefaultParser(); return cmdLineParser.parse(options, commandLineArguments); } private void start(CommandLine cmd) throws IOException, GeneralSecurityException, SQLException { // The port on which the server should run. int port = Integer.valueOf(cmd.getOptionValue(PORT_OPTION)); // The FCM message sender. FcmSender fcmSender = new FcmSender( cmd.getOptionValue(FIREBASE_PROJECT_ID_OPTION), cmd.getOptionValue(SERVICE_ACCOUNT_CREDENTIALS_PATH_OPTION)); // The Capillary encrypter managers. RsaEcdsaEncrypterManager rsaEcdsaEncrypterManager; try (FileInputStream senderSigningKey = new FileInputStream(cmd.getOptionValue(ECDSA_PRIVATE_KEY_PATH_OPTION))) { rsaEcdsaEncrypterManager = new RsaEcdsaEncrypterManager(senderSigningKey); }
WebPushEncrypterManager webPushEncrypterManager = new WebPushEncrypterManager();
google/capillary
lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerAbstractAndroidTest.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerAbstractAndroidTest { private static final String PUBLIC_KEY_AUTH = "public key auth"; private static final String PUBLIC_KEY_NO_AUTH = "public key no auth"; private Context context; private KeyManager keyManager; private String keyManagerUniqueId; private int noAuthKeySerialNumber; private int authKeySerialNumber; /** * Initializes test case-specific state. */ @Before public void setUp() throws GeneralSecurityException,
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerAbstractAndroidTest.java import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerAbstractAndroidTest { private static final String PUBLIC_KEY_AUTH = "public key auth"; private static final String PUBLIC_KEY_NO_AUTH = "public key no auth"; private Context context; private KeyManager keyManager; private String keyManagerUniqueId; private int noAuthKeySerialNumber; private int authKeySerialNumber; /** * Initializes test case-specific state. */ @Before public void setUp() throws GeneralSecurityException,
AuthModeUnavailableException,
google/capillary
lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerAbstractAndroidTest.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerAbstractAndroidTest { private static final String PUBLIC_KEY_AUTH = "public key auth"; private static final String PUBLIC_KEY_NO_AUTH = "public key no auth"; private Context context; private KeyManager keyManager; private String keyManagerUniqueId; private int noAuthKeySerialNumber; private int authKeySerialNumber; /** * Initializes test case-specific state. */ @Before public void setUp() throws GeneralSecurityException, AuthModeUnavailableException,
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/androidTest/java/com/google/capillary/android/KeyManagerAbstractAndroidTest.java import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; @RunWith(AndroidJUnit4.class) public final class KeyManagerAbstractAndroidTest { private static final String PUBLIC_KEY_AUTH = "public key auth"; private static final String PUBLIC_KEY_NO_AUTH = "public key no auth"; private Context context; private KeyManager keyManager; private String keyManagerUniqueId; private int noAuthKeySerialNumber; private int authKeySerialNumber; /** * Initializes test case-specific state. */ @Before public void setUp() throws GeneralSecurityException, AuthModeUnavailableException,
NoSuchKeyException,
google/capillary
lib-android/src/main/java/com/google/capillary/android/AndroidKeyStoreRsaUtils.java
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import com.google.capillary.NoSuchKeyException; import com.google.capillary.RsaEcdsaConstants.Padding; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableKeyException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import javax.security.auth.x500.X500Principal; import org.joda.time.LocalDate;
specBuilder.setUserAuthenticationRequired(true); specBuilder.setUserAuthenticationValidityDurationSeconds(UNLOCK_DURATION_SECONDS); } spec = specBuilder.build(); } else { // API levels 22 and below have to use KeyPairGeneratorSpec to build RSA keys. LocalDate startDate = LocalDate.now(); LocalDate endDate = startDate.plusYears(KEY_DURATION_YEARS); KeyPairGeneratorSpec.Builder specBuilder = new KeyPairGeneratorSpec.Builder(context) .setAlias(keyAlias) .setSubject(new X500Principal("CN=" + keyAlias)) .setSerialNumber(BigInteger.ONE) .setStartDate(startDate.toDate()) .setEndDate(endDate.toDate()); // Only API levels 19 and above allow specifying RSA key parameters. if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { specBuilder.setAlgorithmParameterSpec(rsaSpec); specBuilder.setKeySize(KEY_SIZE); } if (isAuth) { specBuilder.setEncryptionRequired(); } spec = specBuilder.build(); } KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEYSTORE_ANDROID); keyPairGenerator.initialize(spec); keyPairGenerator.generateKeyPair(); } static PublicKey getPublicKey(KeyStore keyStore, String keychainId, boolean isAuth)
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib-android/src/main/java/com/google/capillary/android/AndroidKeyStoreRsaUtils.java import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import com.google.capillary.NoSuchKeyException; import com.google.capillary.RsaEcdsaConstants.Padding; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableKeyException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import javax.security.auth.x500.X500Principal; import org.joda.time.LocalDate; specBuilder.setUserAuthenticationRequired(true); specBuilder.setUserAuthenticationValidityDurationSeconds(UNLOCK_DURATION_SECONDS); } spec = specBuilder.build(); } else { // API levels 22 and below have to use KeyPairGeneratorSpec to build RSA keys. LocalDate startDate = LocalDate.now(); LocalDate endDate = startDate.plusYears(KEY_DURATION_YEARS); KeyPairGeneratorSpec.Builder specBuilder = new KeyPairGeneratorSpec.Builder(context) .setAlias(keyAlias) .setSubject(new X500Principal("CN=" + keyAlias)) .setSerialNumber(BigInteger.ONE) .setStartDate(startDate.toDate()) .setEndDate(endDate.toDate()); // Only API levels 19 and above allow specifying RSA key parameters. if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) { specBuilder.setAlgorithmParameterSpec(rsaSpec); specBuilder.setKeySize(KEY_SIZE); } if (isAuth) { specBuilder.setEncryptionRequired(); } spec = specBuilder.build(); } KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", KEYSTORE_ANDROID); keyPairGenerator.initialize(spec); keyPairGenerator.generateKeyPair(); } static PublicKey getPublicKey(KeyStore keyStore, String keychainId, boolean isAuth)
throws NoSuchKeyException, KeyStoreException {
google/capillary
lib-android/src/main/java/com/google/capillary/android/AndroidKeyStoreRsaUtils.java
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import com.google.capillary.NoSuchKeyException; import com.google.capillary.RsaEcdsaConstants.Padding; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableKeyException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import javax.security.auth.x500.X500Principal; import org.joda.time.LocalDate;
NoSuchKeyException { String alias = toKeyAlias(keychainId, isAuth); checkKeyExists(keyStore, alias); return (PrivateKey) keyStore.getKey(alias, null); } static void deleteKeyPair(KeyStore keyStore, String keychainId, boolean isAuth) throws NoSuchKeyException, KeyStoreException { String alias = toKeyAlias(keychainId, isAuth); checkKeyExists(keyStore, alias); keyStore.deleteEntry(alias); } private static String toKeyAlias(String keychainId, boolean isAuth) { String suffix = isAuth ? AUTH_KEY_ALIAS_SUFFIX : NO_AUTH_KEY_ALIAS_SUFFIX; return keychainId + suffix; } static void checkKeyExists(KeyStore keyStore, String keychainId, boolean isAuth) throws NoSuchKeyException, KeyStoreException { checkKeyExists(keyStore, toKeyAlias(keychainId, isAuth)); } private static void checkKeyExists(KeyStore keyStore, String alias) throws NoSuchKeyException, KeyStoreException { if (!keyStore.containsAlias(alias)) { throw new NoSuchKeyException("android key store has no rsa key pair with alias " + alias); } }
// Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib-android/src/main/java/com/google/capillary/android/AndroidKeyStoreRsaUtils.java import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.KeyPairGeneratorSpec; import android.security.keystore.KeyGenParameterSpec; import android.security.keystore.KeyProperties; import com.google.capillary.NoSuchKeyException; import com.google.capillary.RsaEcdsaConstants.Padding; import java.math.BigInteger; import java.security.InvalidAlgorithmParameterException; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.UnrecoverableKeyException; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.RSAKeyGenParameterSpec; import javax.security.auth.x500.X500Principal; import org.joda.time.LocalDate; NoSuchKeyException { String alias = toKeyAlias(keychainId, isAuth); checkKeyExists(keyStore, alias); return (PrivateKey) keyStore.getKey(alias, null); } static void deleteKeyPair(KeyStore keyStore, String keychainId, boolean isAuth) throws NoSuchKeyException, KeyStoreException { String alias = toKeyAlias(keychainId, isAuth); checkKeyExists(keyStore, alias); keyStore.deleteEntry(alias); } private static String toKeyAlias(String keychainId, boolean isAuth) { String suffix = isAuth ? AUTH_KEY_ALIAS_SUFFIX : NO_AUTH_KEY_ALIAS_SUFFIX; return keychainId + suffix; } static void checkKeyExists(KeyStore keyStore, String keychainId, boolean isAuth) throws NoSuchKeyException, KeyStoreException { checkKeyExists(keyStore, toKeyAlias(keychainId, isAuth)); } private static void checkKeyExists(KeyStore keyStore, String alias) throws NoSuchKeyException, KeyStoreException { if (!keyStore.containsAlias(alias)) { throw new NoSuchKeyException("android key store has no rsa key pair with alias " + alias); } }
static Padding getCompatibleRsaPadding() {
google/capillary
lib/src/test/java/com/google/capillary/RsaEcdsaHybridEncryptTest.java
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // }
import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import com.google.crypto.tink.PublicKeyVerify; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import org.junit.Test;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaHybridEncryptTest { private final PublicKeySign senderSigner; private final PublicKey recipientPublicKey; /** * Creates a new {@link RsaEcdsaHybridEncryptTest} instance. */ public RsaEcdsaHybridEncryptTest() throws GeneralSecurityException, IOException { Config.initialize(); senderSigner = TestUtils.createTestSenderSigner(); recipientPublicKey = TestUtils.createTestRsaPublicKey(); } @Test public void testEncryptDecrypt() throws IOException, GeneralSecurityException { PublicKeyVerify senderVerifier = TestUtils.createTestSenderVerifier(); PrivateKey recipientPrivateKey = TestUtils.createTestRsaPrivateKey(); // Try Encryption/Decryption for each padding mode.
// Path: lib/src/main/java/com/google/capillary/RsaEcdsaConstants.java // public enum Padding { // OAEP("OAEPPadding"), // PKCS1("PKCS1Padding"); // // private static final String PREFIX = "RSA/ECB/"; // // private final String padding; // // Padding(String val) { // padding = val; // } // // /** // * Returns the current padding enum's transformation string that should be used when calling // * {@code javax.crypto.Cipher.getInstance}. // * // * @return the transformation string. // */ // public String getTransformation() { // return PREFIX + padding; // } // } // Path: lib/src/test/java/com/google/capillary/RsaEcdsaHybridEncryptTest.java import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.fail; import com.google.capillary.RsaEcdsaConstants.Padding; import com.google.crypto.tink.HybridDecrypt; import com.google.crypto.tink.HybridEncrypt; import com.google.crypto.tink.PublicKeySign; import com.google.crypto.tink.PublicKeyVerify; import com.google.crypto.tink.subtle.Random; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.PrivateKey; import java.security.PublicKey; import org.junit.Test; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary; @RunWith(JUnit4.class) public final class RsaEcdsaHybridEncryptTest { private final PublicKeySign senderSigner; private final PublicKey recipientPublicKey; /** * Creates a new {@link RsaEcdsaHybridEncryptTest} instance. */ public RsaEcdsaHybridEncryptTest() throws GeneralSecurityException, IOException { Config.initialize(); senderSigner = TestUtils.createTestSenderSigner(); recipientPublicKey = TestUtils.createTestRsaPublicKey(); } @Test public void testEncryptDecrypt() throws IOException, GeneralSecurityException { PublicKeyVerify senderVerifier = TestUtils.createTestSenderVerifier(); PrivateKey recipientPrivateKey = TestUtils.createTestRsaPrivateKey(); // Try Encryption/Decryption for each padding mode.
for (Padding padding : Padding.values()) {
google/capillary
lib-android/src/main/java/com/google/capillary/android/KeyManager.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.VisibleForTesting; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.UUID;
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; /** * Encapsulates the management of Capillary keys. */ public abstract class KeyManager { private static final String AUTH_KEY_SERIAL_NUMBER_KEY = "current_auth_key_serial_number"; private static final String NO_AUTH_KEY_SERIAL_NUMBER_KEY = "current_no_auth_key_serial_number"; private static final String KEYCHAIN_UNIQUE_ID_KEY = "keychain_unique_id"; final Context context; final String keychainId; private final Utils utils; private final SharedPreferences sharedPreferences; private DecrypterManager decrypterManager; /** * Creates a new {@link KeyManager} instance for managing Capillary keys. */ KeyManager(Context context, Utils utils, String keychainId) { this.context = context; this.utils = utils; this.keychainId = keychainId; Context storageContext = utils.getDeviceProtectedStorageContext(context); String prefName = String.format("%s_%s_preferences", getClass().getCanonicalName(), keychainId); sharedPreferences = storageContext.getSharedPreferences(prefName, Context.MODE_PRIVATE); } /** * Provides a {@link DecrypterManager} backed by this {@link KeyManager}. * * @return the {@link DecrypterManager} instance. */ public synchronized DecrypterManager getDecrypterManager() { if (decrypterManager == null) { CiphertextStorage ciphertextStorage = new CiphertextStorage(context, utils, keychainId); decrypterManager = new DecrypterManager(context, this, ciphertextStorage, utils); } return decrypterManager; } private static String toSerialNumberPrefKey(boolean isAuth) { return isAuth ? AUTH_KEY_SERIAL_NUMBER_KEY : NO_AUTH_KEY_SERIAL_NUMBER_KEY; } /** * Generates both auth and no-auth key pairs. * * @throws AuthModeUnavailableException if the user has not enabled authentication * (i.e., a device with no screen lock). * @throws GeneralSecurityException if the key generation fails. */
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/main/java/com/google/capillary/android/KeyManager.java import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.VisibleForTesting; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.UUID; /* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.capillary.android; /** * Encapsulates the management of Capillary keys. */ public abstract class KeyManager { private static final String AUTH_KEY_SERIAL_NUMBER_KEY = "current_auth_key_serial_number"; private static final String NO_AUTH_KEY_SERIAL_NUMBER_KEY = "current_no_auth_key_serial_number"; private static final String KEYCHAIN_UNIQUE_ID_KEY = "keychain_unique_id"; final Context context; final String keychainId; private final Utils utils; private final SharedPreferences sharedPreferences; private DecrypterManager decrypterManager; /** * Creates a new {@link KeyManager} instance for managing Capillary keys. */ KeyManager(Context context, Utils utils, String keychainId) { this.context = context; this.utils = utils; this.keychainId = keychainId; Context storageContext = utils.getDeviceProtectedStorageContext(context); String prefName = String.format("%s_%s_preferences", getClass().getCanonicalName(), keychainId); sharedPreferences = storageContext.getSharedPreferences(prefName, Context.MODE_PRIVATE); } /** * Provides a {@link DecrypterManager} backed by this {@link KeyManager}. * * @return the {@link DecrypterManager} instance. */ public synchronized DecrypterManager getDecrypterManager() { if (decrypterManager == null) { CiphertextStorage ciphertextStorage = new CiphertextStorage(context, utils, keychainId); decrypterManager = new DecrypterManager(context, this, ciphertextStorage, utils); } return decrypterManager; } private static String toSerialNumberPrefKey(boolean isAuth) { return isAuth ? AUTH_KEY_SERIAL_NUMBER_KEY : NO_AUTH_KEY_SERIAL_NUMBER_KEY; } /** * Generates both auth and no-auth key pairs. * * @throws AuthModeUnavailableException if the user has not enabled authentication * (i.e., a device with no screen lock). * @throws GeneralSecurityException if the key generation fails. */
public void generateKeyPairs() throws GeneralSecurityException, AuthModeUnavailableException {
google/capillary
lib-android/src/main/java/com/google/capillary/android/KeyManager.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.VisibleForTesting; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.UUID;
* @throws GeneralSecurityException if the key generation fails. */ public synchronized void generateKeyPair(boolean isAuth) throws AuthModeUnavailableException, GeneralSecurityException { int currentSerialNumber = sharedPreferences.getInt(toSerialNumberPrefKey(isAuth), -1); generateKeyPair(currentSerialNumber + 1, isAuth); } /** * Generates a new Capillary key pair with the given key serial number. */ synchronized boolean generateKeyPair(int newSerialNumber, boolean isAuth) throws AuthModeUnavailableException, GeneralSecurityException { if (isAuth) { utils.checkAuthModeIsAvailable(context); } int currentSerialNumber = sharedPreferences.getInt(toSerialNumberPrefKey(isAuth), -1); // If the requested serial number is older, do not generate the keys. if (newSerialNumber <= currentSerialNumber) { return false; } rawGenerateKeyPair(isAuth); sharedPreferences.edit().putInt(toSerialNumberPrefKey(isAuth), newSerialNumber).apply(); return true; } static String toKeyTypeString(boolean isAuth) { return isAuth ? "Auth" : "NoAuth"; }
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/main/java/com/google/capillary/android/KeyManager.java import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.VisibleForTesting; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryPublicKey; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.ByteString; import java.security.GeneralSecurityException; import java.util.UUID; * @throws GeneralSecurityException if the key generation fails. */ public synchronized void generateKeyPair(boolean isAuth) throws AuthModeUnavailableException, GeneralSecurityException { int currentSerialNumber = sharedPreferences.getInt(toSerialNumberPrefKey(isAuth), -1); generateKeyPair(currentSerialNumber + 1, isAuth); } /** * Generates a new Capillary key pair with the given key serial number. */ synchronized boolean generateKeyPair(int newSerialNumber, boolean isAuth) throws AuthModeUnavailableException, GeneralSecurityException { if (isAuth) { utils.checkAuthModeIsAvailable(context); } int currentSerialNumber = sharedPreferences.getInt(toSerialNumberPrefKey(isAuth), -1); // If the requested serial number is older, do not generate the keys. if (newSerialNumber <= currentSerialNumber) { return false; } rawGenerateKeyPair(isAuth); sharedPreferences.edit().putInt(toSerialNumberPrefKey(isAuth), newSerialNumber).apply(); return true; } static String toKeyTypeString(boolean isAuth) { return isAuth ? "Auth" : "NoAuth"; }
private int checkAndGetSerialNumber(boolean isAuth) throws NoSuchKeyException {
google/capillary
lib-android/src/main/java/com/google/capillary/android/DecrypterManager.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import java.security.UnrecoverableKeyException; import java.util.List;
* @param handler the Capillary handler instance. * @param extra the extra parameters to be passed back to the provided handler. */ public synchronized void decrypt(byte[] ciphertext, CapillaryHandler handler, Object extra) { // Parse the given ciphertext bytes. CapillaryCiphertext capillaryCiphertext; try { capillaryCiphertext = CapillaryCiphertext.parseFrom(ciphertext); } catch (InvalidProtocolBufferException e) { handler.error(CapillaryHandlerErrorCode.MALFORMED_CIPHERTEXT, ciphertext, extra); return; } // Save the ciphertext for later if the decryption key is not ready. if (capillaryCiphertext.getIsAuthKey() && utils.isScreenLocked(context)) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } byte[] rawCiphertext = capillaryCiphertext.getCiphertext().toByteArray(); byte[] data; // Attempt decryption. try { HybridDecrypt decrypter = keyManager.getDecrypter( capillaryCiphertext.getKeychainUniqueId(), capillaryCiphertext.getKeySerialNumber(), capillaryCiphertext.getIsAuthKey()); data = decrypter.decrypt(rawCiphertext, null);
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/main/java/com/google/capillary/android/DecrypterManager.java import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import java.security.UnrecoverableKeyException; import java.util.List; * @param handler the Capillary handler instance. * @param extra the extra parameters to be passed back to the provided handler. */ public synchronized void decrypt(byte[] ciphertext, CapillaryHandler handler, Object extra) { // Parse the given ciphertext bytes. CapillaryCiphertext capillaryCiphertext; try { capillaryCiphertext = CapillaryCiphertext.parseFrom(ciphertext); } catch (InvalidProtocolBufferException e) { handler.error(CapillaryHandlerErrorCode.MALFORMED_CIPHERTEXT, ciphertext, extra); return; } // Save the ciphertext for later if the decryption key is not ready. if (capillaryCiphertext.getIsAuthKey() && utils.isScreenLocked(context)) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } byte[] rawCiphertext = capillaryCiphertext.getCiphertext().toByteArray(); byte[] data; // Attempt decryption. try { HybridDecrypt decrypter = keyManager.getDecrypter( capillaryCiphertext.getKeychainUniqueId(), capillaryCiphertext.getKeySerialNumber(), capillaryCiphertext.getIsAuthKey()); data = decrypter.decrypt(rawCiphertext, null);
} catch (AuthModeUnavailableException e) {
google/capillary
lib-android/src/main/java/com/google/capillary/android/DecrypterManager.java
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // }
import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import java.security.UnrecoverableKeyException; import java.util.List;
// Save the ciphertext for later if the decryption key is not ready. if (capillaryCiphertext.getIsAuthKey() && utils.isScreenLocked(context)) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } byte[] rawCiphertext = capillaryCiphertext.getCiphertext().toByteArray(); byte[] data; // Attempt decryption. try { HybridDecrypt decrypter = keyManager.getDecrypter( capillaryCiphertext.getKeychainUniqueId(), capillaryCiphertext.getKeySerialNumber(), capillaryCiphertext.getIsAuthKey()); data = decrypter.decrypt(rawCiphertext, null); } catch (AuthModeUnavailableException e) { handler.error(CapillaryHandlerErrorCode.AUTH_CIPHER_IN_NO_AUTH_DEVICE, ciphertext, extra); return; } catch (Exception e) { // Needs to catch Exception here to support multiple API levels. // In API levels 23 and above, this happens when the user has enabled authentication, but // hasn't yet authenticated in the lock screen (e.g., added a new unlock code, but hasn't // locked the device yet.). if (VERSION.SDK_INT >= VERSION_CODES.M && e instanceof UserNotAuthenticatedException) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } // All these exceptions refer to missing or corrupt decryption keys.
// Path: lib/src/main/java/com/google/capillary/AuthModeUnavailableException.java // public final class AuthModeUnavailableException extends CapillaryException { // // /** // * Creates a new {@link AuthModeUnavailableException} instance. // * // * @param msg the exception message. // */ // public AuthModeUnavailableException(String msg) { // super(msg); // } // } // // Path: lib/src/main/java/com/google/capillary/NoSuchKeyException.java // public final class NoSuchKeyException extends CapillaryException { // // /** // * Creates a new {@link NoSuchKeyException} object. // * // * @param msg the exception message. // */ // public NoSuchKeyException(String msg) { // super(msg); // } // } // Path: lib-android/src/main/java/com/google/capillary/android/DecrypterManager.java import android.content.Context; import android.os.Build.VERSION; import android.os.Build.VERSION_CODES; import android.security.keystore.KeyPermanentlyInvalidatedException; import android.security.keystore.UserNotAuthenticatedException; import com.google.capillary.AuthModeUnavailableException; import com.google.capillary.NoSuchKeyException; import com.google.capillary.internal.CapillaryCiphertext; import com.google.crypto.tink.HybridDecrypt; import com.google.protobuf.InvalidProtocolBufferException; import java.security.GeneralSecurityException; import java.security.UnrecoverableKeyException; import java.util.List; // Save the ciphertext for later if the decryption key is not ready. if (capillaryCiphertext.getIsAuthKey() && utils.isScreenLocked(context)) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } byte[] rawCiphertext = capillaryCiphertext.getCiphertext().toByteArray(); byte[] data; // Attempt decryption. try { HybridDecrypt decrypter = keyManager.getDecrypter( capillaryCiphertext.getKeychainUniqueId(), capillaryCiphertext.getKeySerialNumber(), capillaryCiphertext.getIsAuthKey()); data = decrypter.decrypt(rawCiphertext, null); } catch (AuthModeUnavailableException e) { handler.error(CapillaryHandlerErrorCode.AUTH_CIPHER_IN_NO_AUTH_DEVICE, ciphertext, extra); return; } catch (Exception e) { // Needs to catch Exception here to support multiple API levels. // In API levels 23 and above, this happens when the user has enabled authentication, but // hasn't yet authenticated in the lock screen (e.g., added a new unlock code, but hasn't // locked the device yet.). if (VERSION.SDK_INT >= VERSION_CODES.M && e instanceof UserNotAuthenticatedException) { ciphertextStorage.save(ciphertext); handler.authCiphertextSavedForLater(ciphertext, extra); return; } // All these exceptions refer to missing or corrupt decryption keys.
if (e instanceof NoSuchKeyException // Thrown by Capillary library.
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/fetcher/FetcherFactory.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTags.java // public final class DfpTags { // // public static final String AD_UNITS = "ad-units"; // public static final String COMPANIES = "companies"; // public static final String CREATIVES = "creatives"; // public static final String CREATIVE_TEMPLATES = "creativetemplates"; // public static final String CUSTOM_TARGETING = "custom-targeting"; // public static final String CUSTOM_TARGETING_KEYS = "custom-targeting-key"; // public static final String CUSTOM_TARGETING_VALUES = "custom-targeting-values"; // public static final String LINE_ITEM_CREATIVE_ASSOCIATIONS = "licas"; // public static final String LINE_ITEMS = "line-items"; // public static final String NETWORKS = "networks"; // public static final String ORDERS = "orders"; // public static final String ORDERS_LINE_ITEMS = "orders-line-items"; // public static final String PLACEMENTS = "placements"; // public static final String PUBLISHER_QUERY_LANGUAGE = "pql"; // public static final String ROLES = "roles"; // public static final String USERS = "users"; // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTypeOverrides.java // public final class DfpTypeOverrides { // // public static final String KEYS = "key"; // public static final String LINE_ITEMS = "lineitem"; // public static final String ORDERS = "order"; // public static final String VALUES = "value"; // }
import com.google.api.ads.dfp.appengine.DfpTags; import com.google.api.ads.dfp.appengine.DfpTypeOverrides; import com.google.common.base.Preconditions; import com.google.inject.Inject; import java.util.Map;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.fetcher; /** * Factory for creating different types of API object fetchers. * * @author Jeff Sham */ public class FetcherFactory { private final Map<String, Fetcher> fetchers; @Inject public FetcherFactory(Map<String, Fetcher> fetchers) { this.fetchers = fetchers; } /** * Returns a fetcher for an API object. * * @param tag the panel to return results to * @param typeOverride determines the type of object to return for panels with multiple types * @return an API object fetcher * @throws IllegalArgumentException if a fetcher cannot be found */ public Fetcher getInstance(String tag, String typeOverride) { Preconditions.checkNotNull(tag); Preconditions.checkNotNull(typeOverride);
// Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTags.java // public final class DfpTags { // // public static final String AD_UNITS = "ad-units"; // public static final String COMPANIES = "companies"; // public static final String CREATIVES = "creatives"; // public static final String CREATIVE_TEMPLATES = "creativetemplates"; // public static final String CUSTOM_TARGETING = "custom-targeting"; // public static final String CUSTOM_TARGETING_KEYS = "custom-targeting-key"; // public static final String CUSTOM_TARGETING_VALUES = "custom-targeting-values"; // public static final String LINE_ITEM_CREATIVE_ASSOCIATIONS = "licas"; // public static final String LINE_ITEMS = "line-items"; // public static final String NETWORKS = "networks"; // public static final String ORDERS = "orders"; // public static final String ORDERS_LINE_ITEMS = "orders-line-items"; // public static final String PLACEMENTS = "placements"; // public static final String PUBLISHER_QUERY_LANGUAGE = "pql"; // public static final String ROLES = "roles"; // public static final String USERS = "users"; // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTypeOverrides.java // public final class DfpTypeOverrides { // // public static final String KEYS = "key"; // public static final String LINE_ITEMS = "lineitem"; // public static final String ORDERS = "order"; // public static final String VALUES = "value"; // } // Path: src/main/java/com/google/api/ads/dfp/appengine/fetcher/FetcherFactory.java import com.google.api.ads.dfp.appengine.DfpTags; import com.google.api.ads.dfp.appengine.DfpTypeOverrides; import com.google.common.base.Preconditions; import com.google.inject.Inject; import java.util.Map; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.fetcher; /** * Factory for creating different types of API object fetchers. * * @author Jeff Sham */ public class FetcherFactory { private final Map<String, Fetcher> fetchers; @Inject public FetcherFactory(Map<String, Fetcher> fetchers) { this.fetchers = fetchers; } /** * Returns a fetcher for an API object. * * @param tag the panel to return results to * @param typeOverride determines the type of object to return for panels with multiple types * @return an API object fetcher * @throws IllegalArgumentException if a fetcher cannot be found */ public Fetcher getInstance(String tag, String typeOverride) { Preconditions.checkNotNull(tag); Preconditions.checkNotNull(typeOverride);
if (tag.equals(DfpTags.ORDERS)) {
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/fetcher/FetcherFactory.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTags.java // public final class DfpTags { // // public static final String AD_UNITS = "ad-units"; // public static final String COMPANIES = "companies"; // public static final String CREATIVES = "creatives"; // public static final String CREATIVE_TEMPLATES = "creativetemplates"; // public static final String CUSTOM_TARGETING = "custom-targeting"; // public static final String CUSTOM_TARGETING_KEYS = "custom-targeting-key"; // public static final String CUSTOM_TARGETING_VALUES = "custom-targeting-values"; // public static final String LINE_ITEM_CREATIVE_ASSOCIATIONS = "licas"; // public static final String LINE_ITEMS = "line-items"; // public static final String NETWORKS = "networks"; // public static final String ORDERS = "orders"; // public static final String ORDERS_LINE_ITEMS = "orders-line-items"; // public static final String PLACEMENTS = "placements"; // public static final String PUBLISHER_QUERY_LANGUAGE = "pql"; // public static final String ROLES = "roles"; // public static final String USERS = "users"; // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTypeOverrides.java // public final class DfpTypeOverrides { // // public static final String KEYS = "key"; // public static final String LINE_ITEMS = "lineitem"; // public static final String ORDERS = "order"; // public static final String VALUES = "value"; // }
import com.google.api.ads.dfp.appengine.DfpTags; import com.google.api.ads.dfp.appengine.DfpTypeOverrides; import com.google.common.base.Preconditions; import com.google.inject.Inject; import java.util.Map;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.fetcher; /** * Factory for creating different types of API object fetchers. * * @author Jeff Sham */ public class FetcherFactory { private final Map<String, Fetcher> fetchers; @Inject public FetcherFactory(Map<String, Fetcher> fetchers) { this.fetchers = fetchers; } /** * Returns a fetcher for an API object. * * @param tag the panel to return results to * @param typeOverride determines the type of object to return for panels with multiple types * @return an API object fetcher * @throws IllegalArgumentException if a fetcher cannot be found */ public Fetcher getInstance(String tag, String typeOverride) { Preconditions.checkNotNull(tag); Preconditions.checkNotNull(typeOverride); if (tag.equals(DfpTags.ORDERS)) {
// Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTags.java // public final class DfpTags { // // public static final String AD_UNITS = "ad-units"; // public static final String COMPANIES = "companies"; // public static final String CREATIVES = "creatives"; // public static final String CREATIVE_TEMPLATES = "creativetemplates"; // public static final String CUSTOM_TARGETING = "custom-targeting"; // public static final String CUSTOM_TARGETING_KEYS = "custom-targeting-key"; // public static final String CUSTOM_TARGETING_VALUES = "custom-targeting-values"; // public static final String LINE_ITEM_CREATIVE_ASSOCIATIONS = "licas"; // public static final String LINE_ITEMS = "line-items"; // public static final String NETWORKS = "networks"; // public static final String ORDERS = "orders"; // public static final String ORDERS_LINE_ITEMS = "orders-line-items"; // public static final String PLACEMENTS = "placements"; // public static final String PUBLISHER_QUERY_LANGUAGE = "pql"; // public static final String ROLES = "roles"; // public static final String USERS = "users"; // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/DfpTypeOverrides.java // public final class DfpTypeOverrides { // // public static final String KEYS = "key"; // public static final String LINE_ITEMS = "lineitem"; // public static final String ORDERS = "order"; // public static final String VALUES = "value"; // } // Path: src/main/java/com/google/api/ads/dfp/appengine/fetcher/FetcherFactory.java import com.google.api.ads.dfp.appengine.DfpTags; import com.google.api.ads.dfp.appengine.DfpTypeOverrides; import com.google.common.base.Preconditions; import com.google.inject.Inject; import java.util.Map; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.fetcher; /** * Factory for creating different types of API object fetchers. * * @author Jeff Sham */ public class FetcherFactory { private final Map<String, Fetcher> fetchers; @Inject public FetcherFactory(Map<String, Fetcher> fetchers) { this.fetchers = fetchers; } /** * Returns a fetcher for an API object. * * @param tag the panel to return results to * @param typeOverride determines the type of object to return for panels with multiple types * @return an API object fetcher * @throws IllegalArgumentException if a fetcher cannot be found */ public Fetcher getInstance(String tag, String typeOverride) { Preconditions.checkNotNull(tag); Preconditions.checkNotNull(typeOverride); if (tag.equals(DfpTags.ORDERS)) {
if (typeOverride.equals(DfpTypeOverrides.ORDERS)) {
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // }
import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.jaxws.factory.DfpServices; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.api.ads.dfp.jaxws.v201403.NetworkServiceInterface; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.inject.Inject; import java.util.List;
// Copyright 2012 Google Inc. All Rights Reserved. package com.google.api.ads.dfp.appengine.util; /** * Utility for making API call to perform operations with network service. * * @author Jeff Sham */ public class Networks { private final Sessions sessions; private final DfpServices dfpServices; private final Predicate<Network> networkPredicate; /** * Constructor. * * @param dfpServices provides DFP services * @param sessions used to create a DFP session * @param networkPredicate predicate used to filter networks */ @Inject public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { this.dfpServices = dfpServices; this.sessions = sessions; this.networkPredicate = networkPredicate; } /** * Gets a list of networks for the user, filtered according to the predicate. * * @param userId The app engine user ID * @return a list of networks * @throws ValidationException if the DFP session could not be created for the user * @throws ApiException_Exception if API call fails * @throws CredentialException if credential cannot be obtained */ public List<Network> get(String userId) throws ValidationException, ApiException_Exception,
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.jaxws.factory.DfpServices; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.api.ads.dfp.jaxws.v201403.NetworkServiceInterface; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import com.google.inject.Inject; import java.util.List; // Copyright 2012 Google Inc. All Rights Reserved. package com.google.api.ads.dfp.appengine.util; /** * Utility for making API call to perform operations with network service. * * @author Jeff Sham */ public class Networks { private final Sessions sessions; private final DfpServices dfpServices; private final Predicate<Network> networkPredicate; /** * Constructor. * * @param dfpServices provides DFP services * @param sessions used to create a DFP session * @param networkPredicate predicate used to filter networks */ @Inject public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { this.dfpServices = dfpServices; this.sessions = sessions; this.networkPredicate = networkPredicate; } /** * Gets a list of networks for the user, filtered according to the predicate. * * @param userId The app engine user ID * @return a list of networks * @throws ValidationException if the DFP session could not be created for the user * @throws ApiException_Exception if API call fails * @throws CredentialException if credential cannot be obtained */ public List<Network> get(String userId) throws ValidationException, ApiException_Exception,
CredentialException {
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/servlet/AuthServlet.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // }
import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet; import com.google.api.client.http.GenericUrl; import com.google.inject.Inject; import com.google.inject.Singleton; import javax.servlet.http.HttpServletRequest;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that handles authorization. Subclass this to make a servlet that walks the user through * the OAuth2 dance before serving. * * @author Jeff Sham */ @Singleton public class AuthServlet extends AbstractAppEngineAuthorizationCodeServlet {
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // Path: src/main/java/com/google/api/ads/dfp/appengine/servlet/AuthServlet.java import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeServlet; import com.google.api.client.http.GenericUrl; import com.google.inject.Inject; import com.google.inject.Singleton; import javax.servlet.http.HttpServletRequest; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that handles authorization. Subclass this to make a servlet that walks the user through * the OAuth2 dance before serving. * * @author Jeff Sham */ @Singleton public class AuthServlet extends AbstractAppEngineAuthorizationCodeServlet {
private final AuthorizationCodeFlowFactory authorizationCodeFlowFactory;
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/util/Sessions.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialFactory.java // public class CredentialFactory { // // private final String clientId; // private final String clientSecret; // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // // @Inject // public CredentialFactory(CredentialStore credentialStore, HttpTransport httpTransport, // JsonFactory jsonFactory, @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret) { // this.clientId = clientId; // this.clientSecret = clientSecret; // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // } // // /** // * Fetch the OAuth2 credential from the App Engine Datastore. // * // * @param userId the App Engine assigned user ID // * @return the oAuth2 credential // * @throws CredentialException if the credential cannot be obtained // */ // public Credential getInstance(String userId) throws CredentialException { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // GoogleCredential credential = new GoogleCredential.Builder() // .setJsonFactory(jsonFactory) // .setTransport(httpTransport) // .setClientSecrets(clientId, clientSecret) // .build(); // try { // credentialStore.load(userId, credential); // try { // credential.refreshToken(); // } catch (IOException e) { // credentialStore.delete(userId, credential); // throw new CredentialException("Credential cannot be refreshed.", e); // } // } catch (IOException e) { // throw new CredentialException("Credential cannot be loaded.", e); // } // return credential; // } // }
import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.oauth.CredentialFactory; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import com.google.inject.Inject; import com.google.inject.name.Named;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.util; /** * {@code Sessions} is used to get DFP sessions for an App Engine application. * * Typical usage is: <code>DfpSession session = Sessions.get(12345, 'APP_ENGINE_USER_ID');</code> * * Only use the get method without a network code if you know the API call can accept the call * without one (i.e. MakeTestNetwork). * * <code>DfpSession session = Sessions.get('APP_ENGINE_USER_ID');</code> * * @author Jeff Sham */ public class Sessions { private final String applicationName;
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialFactory.java // public class CredentialFactory { // // private final String clientId; // private final String clientSecret; // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // // @Inject // public CredentialFactory(CredentialStore credentialStore, HttpTransport httpTransport, // JsonFactory jsonFactory, @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret) { // this.clientId = clientId; // this.clientSecret = clientSecret; // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // } // // /** // * Fetch the OAuth2 credential from the App Engine Datastore. // * // * @param userId the App Engine assigned user ID // * @return the oAuth2 credential // * @throws CredentialException if the credential cannot be obtained // */ // public Credential getInstance(String userId) throws CredentialException { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // GoogleCredential credential = new GoogleCredential.Builder() // .setJsonFactory(jsonFactory) // .setTransport(httpTransport) // .setClientSecrets(clientId, clientSecret) // .build(); // try { // credentialStore.load(userId, credential); // try { // credential.refreshToken(); // } catch (IOException e) { // credentialStore.delete(userId, credential); // throw new CredentialException("Credential cannot be refreshed.", e); // } // } catch (IOException e) { // throw new CredentialException("Credential cannot be loaded.", e); // } // return credential; // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Sessions.java import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.oauth.CredentialFactory; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import com.google.inject.Inject; import com.google.inject.name.Named; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.util; /** * {@code Sessions} is used to get DFP sessions for an App Engine application. * * Typical usage is: <code>DfpSession session = Sessions.get(12345, 'APP_ENGINE_USER_ID');</code> * * Only use the get method without a network code if you know the API call can accept the call * without one (i.e. MakeTestNetwork). * * <code>DfpSession session = Sessions.get('APP_ENGINE_USER_ID');</code> * * @author Jeff Sham */ public class Sessions { private final String applicationName;
private final CredentialFactory credentialFactory;
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/util/Sessions.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialFactory.java // public class CredentialFactory { // // private final String clientId; // private final String clientSecret; // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // // @Inject // public CredentialFactory(CredentialStore credentialStore, HttpTransport httpTransport, // JsonFactory jsonFactory, @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret) { // this.clientId = clientId; // this.clientSecret = clientSecret; // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // } // // /** // * Fetch the OAuth2 credential from the App Engine Datastore. // * // * @param userId the App Engine assigned user ID // * @return the oAuth2 credential // * @throws CredentialException if the credential cannot be obtained // */ // public Credential getInstance(String userId) throws CredentialException { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // GoogleCredential credential = new GoogleCredential.Builder() // .setJsonFactory(jsonFactory) // .setTransport(httpTransport) // .setClientSecrets(clientId, clientSecret) // .build(); // try { // credentialStore.load(userId, credential); // try { // credential.refreshToken(); // } catch (IOException e) { // credentialStore.delete(userId, credential); // throw new CredentialException("Credential cannot be refreshed.", e); // } // } catch (IOException e) { // throw new CredentialException("Credential cannot be loaded.", e); // } // return credential; // } // }
import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.oauth.CredentialFactory; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import com.google.inject.Inject; import com.google.inject.name.Named;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.util; /** * {@code Sessions} is used to get DFP sessions for an App Engine application. * * Typical usage is: <code>DfpSession session = Sessions.get(12345, 'APP_ENGINE_USER_ID');</code> * * Only use the get method without a network code if you know the API call can accept the call * without one (i.e. MakeTestNetwork). * * <code>DfpSession session = Sessions.get('APP_ENGINE_USER_ID');</code> * * @author Jeff Sham */ public class Sessions { private final String applicationName; private final CredentialFactory credentialFactory; @Inject public Sessions(CredentialFactory credentialFactory, @Named("applicationName") String applicationName) { this.credentialFactory = credentialFactory; this.applicationName = applicationName; } /** * Creates a {@link DfpSession} from the user's stored credentials and specified network. * * @param networkCode the user's network code * @param userId the App Engine assigned user ID * @return session the DFP session * @throws ValidationException if the DFP session could not be validated and created * @throws CredentialException if credential cannot be obtained */ public DfpSession get(String networkCode, String userId) throws ValidationException,
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialFactory.java // public class CredentialFactory { // // private final String clientId; // private final String clientSecret; // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // // @Inject // public CredentialFactory(CredentialStore credentialStore, HttpTransport httpTransport, // JsonFactory jsonFactory, @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret) { // this.clientId = clientId; // this.clientSecret = clientSecret; // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // } // // /** // * Fetch the OAuth2 credential from the App Engine Datastore. // * // * @param userId the App Engine assigned user ID // * @return the oAuth2 credential // * @throws CredentialException if the credential cannot be obtained // */ // public Credential getInstance(String userId) throws CredentialException { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // GoogleCredential credential = new GoogleCredential.Builder() // .setJsonFactory(jsonFactory) // .setTransport(httpTransport) // .setClientSecrets(clientId, clientSecret) // .build(); // try { // credentialStore.load(userId, credential); // try { // credential.refreshToken(); // } catch (IOException e) { // credentialStore.delete(userId, credential); // throw new CredentialException("Credential cannot be refreshed.", e); // } // } catch (IOException e) { // throw new CredentialException("Credential cannot be loaded.", e); // } // return credential; // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Sessions.java import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.oauth.CredentialFactory; import com.google.api.ads.dfp.lib.client.DfpSession; import com.google.api.client.auth.oauth2.Credential; import com.google.inject.Inject; import com.google.inject.name.Named; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.util; /** * {@code Sessions} is used to get DFP sessions for an App Engine application. * * Typical usage is: <code>DfpSession session = Sessions.get(12345, 'APP_ENGINE_USER_ID');</code> * * Only use the get method without a network code if you know the API call can accept the call * without one (i.e. MakeTestNetwork). * * <code>DfpSession session = Sessions.get('APP_ENGINE_USER_ID');</code> * * @author Jeff Sham */ public class Sessions { private final String applicationName; private final CredentialFactory credentialFactory; @Inject public Sessions(CredentialFactory credentialFactory, @Named("applicationName") String applicationName) { this.credentialFactory = credentialFactory; this.applicationName = applicationName; } /** * Creates a {@link DfpSession} from the user's stored credentials and specified network. * * @param networkCode the user's network code * @param userId the App Engine assigned user ID * @return session the DFP session * @throws ValidationException if the DFP session could not be validated and created * @throws CredentialException if credential cannot be obtained */ public DfpSession get(String networkCode, String userId) throws ValidationException,
CredentialException {
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that allows users to create a new DFP test network. * * @author Jeff Sham */ @Singleton @SuppressWarnings("serial") public class CreateNetworkServlet extends AuthServlet {
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that allows users to create a new DFP test network. * * @author Jeff Sham */ @Singleton @SuppressWarnings("serial") public class CreateNetworkServlet extends AuthServlet {
private final Networks networks;
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that allows users to create a new DFP test network. * * @author Jeff Sham */ @Singleton @SuppressWarnings("serial") public class CreateNetworkServlet extends AuthServlet { private final Networks networks; private final UserService userService; /** * Constructor. * * @param networks used to create networks * @param userService the App Engine service for user management * @param authorizationCodeFlowFactory used to get an OAuth2 flow * @param redirectUrl where to direct the user once authorization is done */ @Inject public CreateNetworkServlet(Networks networks, UserService userService,
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Servlet that allows users to create a new DFP test network. * * @author Jeff Sham */ @Singleton @SuppressWarnings("serial") public class CreateNetworkServlet extends AuthServlet { private final Networks networks; private final UserService userService; /** * Constructor. * * @param networks used to create networks * @param userService the App Engine service for user management * @param authorizationCodeFlowFactory used to get an OAuth2 flow * @param redirectUrl where to direct the user once authorization is done */ @Inject public CreateNetworkServlet(Networks networks, UserService userService,
AuthorizationCodeFlowFactory authorizationCodeFlowFactory,
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException;
public CreateNetworkServlet(Networks networks, UserService userService, AuthorizationCodeFlowFactory authorizationCodeFlowFactory, @Named("redirectUrl") String redirectUrl) { super(authorizationCodeFlowFactory, redirectUrl); this.networks = networks; this.userService = userService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/newNetwork.jsp"); requestDispatcher.forward(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/newNetwork.jsp"); if (req.getParameter("createNetwork") != null) { try { Network newNetwork = networks.make(userService.getCurrentUser().getUserId()); resp.sendRedirect("/index?newNetworkCode=" + newNetwork.getNetworkCode()); return; } catch (ApiException_Exception e) { req.setAttribute("error", true); } catch (ValidationException e) { req.setAttribute("error", true);
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/CredentialException.java // public class CredentialException extends Exception { // // /** // * Constructor. // * // * @param message the exception message // * @param exception the underlying exception // */ // public CredentialException(String message, Throwable exception) { // super(message, exception); // } // } // // Path: src/main/java/com/google/api/ads/dfp/appengine/util/Networks.java // public class Networks { // // private final Sessions sessions; // private final DfpServices dfpServices; // private final Predicate<Network> networkPredicate; // // /** // * Constructor. // * // * @param dfpServices provides DFP services // * @param sessions used to create a DFP session // * @param networkPredicate predicate used to filter networks // */ // @Inject // public Networks(DfpServices dfpServices, Sessions sessions, Predicate<Network> networkPredicate) { // this.dfpServices = dfpServices; // this.sessions = sessions; // this.networkPredicate = networkPredicate; // } // // /** // * Gets a list of networks for the user, filtered according to the predicate. // * // * @param userId The app engine user ID // * @return a list of networks // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public List<Network> get(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return Lists.newArrayList( // Collections2.filter(networkService.getAllNetworks(), networkPredicate)); // } // // /** // * Make a new test network. // * // * @param userId The app engine user ID // * @return the created network // * @throws ValidationException if the DFP session could not be created for the user // * @throws ApiException_Exception if API call fails // * @throws CredentialException if credential cannot be obtained // */ // public Network make(String userId) throws ValidationException, ApiException_Exception, // CredentialException { // DfpSession session = sessions.get(userId); // NetworkServiceInterface networkService = // dfpServices.get(session, NetworkServiceInterface.class); // return networkService.makeTestNetwork(); // } // } // Path: src/main/java/com/google/api/ads/dfp/appengine/servlet/CreateNetworkServlet.java import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.ads.common.lib.exception.ValidationException; import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.ads.dfp.appengine.oauth.CredentialException; import com.google.api.ads.dfp.appengine.util.Networks; import com.google.api.ads.dfp.jaxws.v201403.ApiException_Exception; import com.google.api.ads.dfp.jaxws.v201403.Network; import com.google.appengine.api.users.UserService; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; public CreateNetworkServlet(Networks networks, UserService userService, AuthorizationCodeFlowFactory authorizationCodeFlowFactory, @Named("redirectUrl") String redirectUrl) { super(authorizationCodeFlowFactory, redirectUrl); this.networks = networks; this.userService = userService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/newNetwork.jsp"); requestDispatcher.forward(req, resp); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext servletContext = getServletContext(); RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/newNetwork.jsp"); if (req.getParameter("createNetwork") != null) { try { Network newNetwork = networks.make(userService.getCurrentUser().getUserId()); resp.sendRedirect("/index?newNetworkCode=" + newNetwork.getNetworkCode()); return; } catch (ApiException_Exception e) { req.setAttribute("error", true); } catch (ValidationException e) { req.setAttribute("error", true);
} catch (CredentialException e) {
googleads/googleads-dfp-java-dfp-playground
src/main/java/com/google/api/ads/dfp/appengine/servlet/OAuth2CallbackServlet.java
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // }
import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeCallbackServlet; import com.google.api.client.http.GenericUrl; import com.google.inject.Inject; import com.google.inject.name.Named; import java.io.IOException; import java.util.logging.Logger; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
// Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Holds information used in the authorization flow, such as which URL to redirect to on * success/failure. * * @author Jeff Sham */ @Singleton public class OAuth2CallbackServlet extends AbstractAppEngineAuthorizationCodeCallbackServlet { private static final Logger LOG = Logger.getLogger(OAuth2CallbackServlet.class.getName());
// Path: src/main/java/com/google/api/ads/dfp/appengine/oauth/AuthorizationCodeFlowFactory.java // public class AuthorizationCodeFlowFactory { // // private final CredentialStore credentialStore; // private final HttpTransport httpTransport; // private final JsonFactory jsonFactory; // private final String clientId; // private final String clientSecret; // private final String scope; // // @Inject // public AuthorizationCodeFlowFactory(CredentialStore credentialStore, // JsonFactory jsonFactory, // HttpTransport httpTransport, // @Named("clientId") String clientId, // @Named("clientSecret") String clientSecret, // @Named("scope") String scope) { // this.credentialStore = credentialStore; // this.httpTransport = httpTransport; // this.jsonFactory = jsonFactory; // this.clientId = clientId; // this.clientSecret = clientSecret; // this.scope = scope; // } // // /** // * Returns a fetcher for an API object. // * // * @return a Google authorization code flow // */ // public GoogleAuthorizationCodeFlow getInstance() { // Preconditions.checkNotNull(clientId); // Preconditions.checkNotNull(clientSecret); // return new GoogleAuthorizationCodeFlow.Builder( // httpTransport, // jsonFactory, // clientId, // clientSecret, // Lists.newArrayList(scope)) // .setCredentialStore(credentialStore) // .setApprovalPrompt("force") // .setAccessType("offline") // .build(); // } // // } // Path: src/main/java/com/google/api/ads/dfp/appengine/servlet/OAuth2CallbackServlet.java import com.google.api.ads.dfp.appengine.oauth.AuthorizationCodeFlowFactory; import com.google.api.client.auth.oauth2.AuthorizationCodeFlow; import com.google.api.client.auth.oauth2.AuthorizationCodeResponseUrl; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.extensions.appengine.auth.oauth2.AbstractAppEngineAuthorizationCodeCallbackServlet; import com.google.api.client.http.GenericUrl; import com.google.inject.Inject; import com.google.inject.name.Named; import java.io.IOException; import java.util.logging.Logger; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; // Copyright 2012 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.api.ads.dfp.appengine.servlet; /** * Holds information used in the authorization flow, such as which URL to redirect to on * success/failure. * * @author Jeff Sham */ @Singleton public class OAuth2CallbackServlet extends AbstractAppEngineAuthorizationCodeCallbackServlet { private static final Logger LOG = Logger.getLogger(OAuth2CallbackServlet.class.getName());
private final AuthorizationCodeFlowFactory authorizationCodeFlowFactory;
itsmartin/TesseractUHC
src/com/martinbrook/tesseractuhc/UhcTeam.java
// Path: src/com/martinbrook/tesseractuhc/startpoint/UhcStartPoint.java // public abstract class UhcStartPoint { // protected Location location; // private UhcTeam team = null; // protected int number; // protected boolean hasChest = true; // // public UhcStartPoint(int number, Location location, boolean hasChest) { // this.location=location; // this.number=number; // this.hasChest = hasChest; // } // // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public UhcTeam getTeam() { // return team; // } // // public void setTeam(UhcTeam team) { // this.team = team; // } // // public double getX() { return location.getX(); } // public double getY() { return location.getY(); } // public double getZ() { return location.getZ(); } // // public int getNumber() { // return number; // } // // // // // /** // * Build a starting trough at this start point, and puts a starter chest and sign there. // * // */ // public abstract void buildStartingTrough(); // public abstract Block getChestBlock(); // public abstract Block getSignBlock(); // // public boolean hasChest() { // return hasChest; // } // // // /** // * Empty the starting chest // */ // public void emptyChest() { // if (!hasChest) return; // this.fillChest(new ItemStack[27]); // } // // /** // * Fill the starting chest with specified contents // */ // public void fillChest(ItemStack[] items) { // if (!hasChest) return; // Block b = getChestBlock(); // if (b.getType() != Material.CHEST) b.setType(Material.CHEST); // // Inventory chest = ((Chest) b.getState()).getBlockInventory(); // chest.setContents(items); // } // // protected void placeChest() { // if (!hasChest) return; // Block chestBlock = this.getChestBlock(); // if (chestBlock.getType() != Material.CHEST) chestBlock.setType(Material.CHEST); // } // // /** // * Make a default start sign // */ // public void makeSign() { // if (team == null) // makeSign("Start #" + number); // else // makeSign(team.getName()); // } // // /** // * Make a start sign with specific text // * // * @param text The text to write on the sign // */ // public void makeSign(String text) { // Block b = getSignBlock(); // b.setType(Material.SIGN_POST); // // Block b1 = b.getRelative(0, -1, 0); // b1.setType(Material.GLASS); // // BlockState bs = b.getState(); // if (!(bs instanceof Sign)) return; // // Sign s = (Sign) bs; // String[] t = MatchUtils.signWrite(text); // // s.setLine(0, t[0]); // s.setLine(1, t[1]); // s.setLine(2, t[2]); // s.setLine(3, t[3]); // // s.update(); // } // // // }
import java.util.HashSet; import org.bukkit.ChatColor; import com.martinbrook.tesseractuhc.startpoint.UhcStartPoint;
package com.martinbrook.tesseractuhc; public class UhcTeam { private String identifier; private String name;
// Path: src/com/martinbrook/tesseractuhc/startpoint/UhcStartPoint.java // public abstract class UhcStartPoint { // protected Location location; // private UhcTeam team = null; // protected int number; // protected boolean hasChest = true; // // public UhcStartPoint(int number, Location location, boolean hasChest) { // this.location=location; // this.number=number; // this.hasChest = hasChest; // } // // // public Location getLocation() { // return location; // } // // public void setLocation(Location location) { // this.location = location; // } // // public UhcTeam getTeam() { // return team; // } // // public void setTeam(UhcTeam team) { // this.team = team; // } // // public double getX() { return location.getX(); } // public double getY() { return location.getY(); } // public double getZ() { return location.getZ(); } // // public int getNumber() { // return number; // } // // // // // /** // * Build a starting trough at this start point, and puts a starter chest and sign there. // * // */ // public abstract void buildStartingTrough(); // public abstract Block getChestBlock(); // public abstract Block getSignBlock(); // // public boolean hasChest() { // return hasChest; // } // // // /** // * Empty the starting chest // */ // public void emptyChest() { // if (!hasChest) return; // this.fillChest(new ItemStack[27]); // } // // /** // * Fill the starting chest with specified contents // */ // public void fillChest(ItemStack[] items) { // if (!hasChest) return; // Block b = getChestBlock(); // if (b.getType() != Material.CHEST) b.setType(Material.CHEST); // // Inventory chest = ((Chest) b.getState()).getBlockInventory(); // chest.setContents(items); // } // // protected void placeChest() { // if (!hasChest) return; // Block chestBlock = this.getChestBlock(); // if (chestBlock.getType() != Material.CHEST) chestBlock.setType(Material.CHEST); // } // // /** // * Make a default start sign // */ // public void makeSign() { // if (team == null) // makeSign("Start #" + number); // else // makeSign(team.getName()); // } // // /** // * Make a start sign with specific text // * // * @param text The text to write on the sign // */ // public void makeSign(String text) { // Block b = getSignBlock(); // b.setType(Material.SIGN_POST); // // Block b1 = b.getRelative(0, -1, 0); // b1.setType(Material.GLASS); // // BlockState bs = b.getState(); // if (!(bs instanceof Sign)) return; // // Sign s = (Sign) bs; // String[] t = MatchUtils.signWrite(text); // // s.setLine(0, t[0]); // s.setLine(1, t[1]); // s.setLine(2, t[2]); // s.setLine(3, t[3]); // // s.update(); // } // // // } // Path: src/com/martinbrook/tesseractuhc/UhcTeam.java import java.util.HashSet; import org.bukkit.ChatColor; import com.martinbrook.tesseractuhc.startpoint.UhcStartPoint; package com.martinbrook.tesseractuhc; public class UhcTeam { private String identifier; private String name;
private UhcStartPoint startPoint;
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/uav/JavaController.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; }
import java.io.IOException; import java.util.ArrayList; import BlueTurtle.gui.GUIController.ASAT; import lombok.Getter; import lombok.Setter;
package BlueTurtle.uav; /** * JavaController controls the analyser to make it analyse java code. It * constructs an AnalyserCommand for every ASAT which has to be run and passes * this to the analyser. * * @author BlueTurtle. * */ public class JavaController implements Controller { @Getter @Setter private static String userDir = System.getProperty("user.dir"); //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> checkStyleOutputFiles; //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> pmdOutputFiles; //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> findBugsOutputFiles; //NOPMD - caused by lombok. /** * Execute controller. A command is constructed for every ASAT which needs * to be run. * * @throws IOException * throws an exception if a problem is encountered when * executing the commands. */ public void execute() throws IOException { new JSONFormatter().format(); } /** * Set the output paths for the ASAT. * * @param asat * the ASAT type. * @param filePaths * the list of output file paths. */
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // Path: src/main/java/BlueTurtle/uav/JavaController.java import java.io.IOException; import java.util.ArrayList; import BlueTurtle.gui.GUIController.ASAT; import lombok.Getter; import lombok.Setter; package BlueTurtle.uav; /** * JavaController controls the analyser to make it analyse java code. It * constructs an AnalyserCommand for every ASAT which has to be run and passes * this to the analyser. * * @author BlueTurtle. * */ public class JavaController implements Controller { @Getter @Setter private static String userDir = System.getProperty("user.dir"); //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> checkStyleOutputFiles; //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> pmdOutputFiles; //NOPMD - caused by lombok. @Getter @Setter private static ArrayList<String> findBugsOutputFiles; //NOPMD - caused by lombok. /** * Execute controller. A command is constructed for every ASAT which needs * to be run. * * @throws IOException * throws an exception if a problem is encountered when * executing the commands. */ public void execute() throws IOException { new JSONFormatter().format(); } /** * Set the output paths for the ASAT. * * @param asat * the ASAT type. * @param filePaths * the list of output file paths. */
public static void setASATOutputFiles(ASAT asat, ArrayList<String> filePaths) {
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/parsers/FindBugsXMLParser.java
// Path: src/main/java/BlueTurtle/warnings/FindBugsWarning.java // public class FindBugsWarning extends Warning { // // // @Getter @Setter private String category; // @Getter @Setter private String priority; // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * @param category // * the category of the warning. // * @param priority // * the priority of the warning. // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public FindBugsWarning(String filePath, String filename, int line, String message, String category, String priority, String ruleName, String classification) { // super(filePath, filename, line, "FindBugs", ruleName, message, classification); // setCategory(category); // setPriority(priority); // } // // // /** // * Check whether two FindBugs warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof FindBugsWarning)) { // return false; // } // // FindBugsWarning that = (FindBugsWarning) other; // // return (filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && category.equals(that.category) && classification.equals(that.classification) // && priority.equals(that.priority) && type.equals(that.type) && ruleName.equals(that.ruleName)); // } // // /** // * HashCode for the FindBugsWarning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, category, priority, ruleName, classification); // } // // /** // * toString method for FindBugsWarning. // */ // @Override // public String toString() { // return "FindBugsWarning [lineNumber=" + line + ", message=" + message + ", category=" + category // + ", priority=" + priority + ", classification=" // + classification + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath // + ", ruleName=" + ruleName + "]"; // } // // }
import java.io.File; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.FindBugsWarning; import BlueTurtle.warnings.Warning;
// The message contained by the warning. String message = warningElement.getAttribute("message"); // The category of warning. String category = warningElement.getAttribute("category"); // The priority of warning, can be high or low. String priority = warningElement.getAttribute("priority"); // line number where the warning is located. int line = Integer.parseInt(warningElement.getAttribute("lineNumber")); // Get the category of the warning. String ruleName = warningElement.getAttribute("type"); String classification = classify(ruleName); try { // replace the dot in the file name with file separator. String fileNWithSep = fileName.replaceAll("\\.", Matcher.quoteReplacement(File.separator)) + ".java"; // for-loop in stream. String filePath = ProjectInfoFinder.getClassPaths().stream().filter(p -> p.endsWith(fileNWithSep)) .findFirst().get(); // Get the name of the file where the warning is from. String finalFileName = fileNWithSep.substring(fileNWithSep.lastIndexOf(File.separatorChar) + 1, fileNWithSep.length()); // Construct the new FindBugsWarning.
// Path: src/main/java/BlueTurtle/warnings/FindBugsWarning.java // public class FindBugsWarning extends Warning { // // // @Getter @Setter private String category; // @Getter @Setter private String priority; // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * @param category // * the category of the warning. // * @param priority // * the priority of the warning. // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public FindBugsWarning(String filePath, String filename, int line, String message, String category, String priority, String ruleName, String classification) { // super(filePath, filename, line, "FindBugs", ruleName, message, classification); // setCategory(category); // setPriority(priority); // } // // // /** // * Check whether two FindBugs warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof FindBugsWarning)) { // return false; // } // // FindBugsWarning that = (FindBugsWarning) other; // // return (filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && category.equals(that.category) && classification.equals(that.classification) // && priority.equals(that.priority) && type.equals(that.type) && ruleName.equals(that.ruleName)); // } // // /** // * HashCode for the FindBugsWarning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, category, priority, ruleName, classification); // } // // /** // * toString method for FindBugsWarning. // */ // @Override // public String toString() { // return "FindBugsWarning [lineNumber=" + line + ", message=" + message + ", category=" + category // + ", priority=" + priority + ", classification=" // + classification + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath // + ", ruleName=" + ruleName + "]"; // } // // } // Path: src/main/java/BlueTurtle/parsers/FindBugsXMLParser.java import java.io.File; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.FindBugsWarning; import BlueTurtle.warnings.Warning; // The message contained by the warning. String message = warningElement.getAttribute("message"); // The category of warning. String category = warningElement.getAttribute("category"); // The priority of warning, can be high or low. String priority = warningElement.getAttribute("priority"); // line number where the warning is located. int line = Integer.parseInt(warningElement.getAttribute("lineNumber")); // Get the category of the warning. String ruleName = warningElement.getAttribute("type"); String classification = classify(ruleName); try { // replace the dot in the file name with file separator. String fileNWithSep = fileName.replaceAll("\\.", Matcher.quoteReplacement(File.separator)) + ".java"; // for-loop in stream. String filePath = ProjectInfoFinder.getClassPaths().stream().filter(p -> p.endsWith(fileNWithSep)) .findFirst().get(); // Get the name of the file where the warning is from. String finalFileName = fileNWithSep.substring(fileNWithSep.lastIndexOf(File.separatorChar) + 1, fileNWithSep.length()); // Construct the new FindBugsWarning.
FindBugsWarning fbw = new FindBugsWarning(filePath, finalFileName, line, message, category, priority,
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/summarizers/ComponentSummarizer.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; }
import java.util.ArrayList; import java.util.List; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController.ASAT; import BlueTurtle.warnings.Warning; import lombok.Getter;
package BlueTurtle.summarizers; /** * This class can be used to summarise the warnings for a specific component. * * @author BlueTurtle. * */ public class ComponentSummarizer extends Summarizer { @Getter private String fileName; @Getter private String filePath; @Getter private List<Warning> warningList; @Getter private int loc; /** * Constructor. * * @param fileName * the name of the component. * @param filePath * the path to the component. * @param packageName * the name of the package where the component is from. */ public ComponentSummarizer(String fileName, String filePath, String packageName) { super(packageName); this.fileName = fileName; this.filePath = filePath; this.loc = ProjectInfoFinder.getClassLocs().get(filePath); this.warningList = new ArrayList<Warning>(); } /** * Summarise the warnings. * * @param warnings * the list of warnings to be summarized. */ @Override public void summarise(List<Warning> warnings) { for (Warning w : warnings) { String pn = ProjectInfoFinder.getClassPackage().get(w.getFilePath()); if (w.getFileName().equals(getFileName()) && pn.equals(getPackageName())) { String warningType = w.getType(); if (!warningTypes.contains(warningType)) { warningTypes.add(w.getType()); } warningList.add(w);
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // Path: src/main/java/BlueTurtle/summarizers/ComponentSummarizer.java import java.util.ArrayList; import java.util.List; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController.ASAT; import BlueTurtle.warnings.Warning; import lombok.Getter; package BlueTurtle.summarizers; /** * This class can be used to summarise the warnings for a specific component. * * @author BlueTurtle. * */ public class ComponentSummarizer extends Summarizer { @Getter private String fileName; @Getter private String filePath; @Getter private List<Warning> warningList; @Getter private int loc; /** * Constructor. * * @param fileName * the name of the component. * @param filePath * the path to the component. * @param packageName * the name of the package where the component is from. */ public ComponentSummarizer(String fileName, String filePath, String packageName) { super(packageName); this.fileName = fileName; this.filePath = filePath; this.loc = ProjectInfoFinder.getClassLocs().get(filePath); this.warningList = new ArrayList<Warning>(); } /** * Summarise the warnings. * * @param warnings * the list of warnings to be summarized. */ @Override public void summarise(List<Warning> warnings) { for (Warning w : warnings) { String pn = ProjectInfoFinder.getClassPackage().get(w.getFilePath()); if (w.getFileName().equals(getFileName()) && pn.equals(getPackageName())) { String warningType = w.getType(); if (!warningTypes.contains(warningType)) { warningTypes.add(w.getType()); } warningList.add(w);
incrementNumberOfWarnings(ASAT.valueOf(warningType));
ClintonCao/UnifiedASATVisualizer
src/test/java/BlueTurtle/uav/JavaControllerTest.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // } // // Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController; import BlueTurtle.gui.GUIController.ASAT;
package BlueTurtle.uav; /** * Test for the JavaController class. * * @author BlueTurtle. * */ public class JavaControllerTest { private String userDir = System.getProperty("user.dir"); private ArrayList<String> checkstyleList = new ArrayList<String>(); private ArrayList<String> pmdList = new ArrayList<String>(); private ArrayList<String> findBugsList = new ArrayList<String>(); private String checkStyleOutputFilePath = userDir + "/src/test/resources/exampleCheckstyle1.xml"; private String pmdOutputFilePath = userDir + "/src/test/resources/examplePmd1.xml"; private String findBugsOutputFilePath = userDir + "/src/test/resources/exampleFindbugs1.xml"; /** * Clear the attributes of JavaController. * * @throws IOException * throws an exception if there was a problem encounterd while * reading the files. */ @Before public void setUp() throws IOException {
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // } // // Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // Path: src/test/java/BlueTurtle/uav/JavaControllerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController; import BlueTurtle.gui.GUIController.ASAT; package BlueTurtle.uav; /** * Test for the JavaController class. * * @author BlueTurtle. * */ public class JavaControllerTest { private String userDir = System.getProperty("user.dir"); private ArrayList<String> checkstyleList = new ArrayList<String>(); private ArrayList<String> pmdList = new ArrayList<String>(); private ArrayList<String> findBugsList = new ArrayList<String>(); private String checkStyleOutputFilePath = userDir + "/src/test/resources/exampleCheckstyle1.xml"; private String pmdOutputFilePath = userDir + "/src/test/resources/examplePmd1.xml"; private String findBugsOutputFilePath = userDir + "/src/test/resources/exampleFindbugs1.xml"; /** * Clear the attributes of JavaController. * * @throws IOException * throws an exception if there was a problem encounterd while * reading the files. */ @Before public void setUp() throws IOException {
GUIController.setProjectPath("test");
ClintonCao/UnifiedASATVisualizer
src/test/java/BlueTurtle/uav/JavaControllerTest.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // } // // Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController; import BlueTurtle.gui.GUIController.ASAT;
ProjectInfoFinder.getClassPackage().clear(); } /** * Test that the user direction path is the same. */ @Test public void testUserDir() { String expected = userDir; String actual = JavaController.getUserDir(); assertEquals(expected, actual); } /** * Test that all files are null at first. */ @Test public void allFilesStringsAreNull() { assertTrue(JavaController.getCheckStyleOutputFiles() == null && JavaController.getPmdOutputFiles() == null && JavaController.getFindBugsOutputFiles() == null); } /** * Test changing CheckStyle list of output file. */ @Test public void testChangingCheckStyleOutputFile() { ArrayList<String> list = JavaController.getCheckStyleOutputFiles(); ArrayList<String> newList = new ArrayList<String>(); newList.add("test path for checkstyle");
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // } // // Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // Path: src/test/java/BlueTurtle/uav/JavaControllerTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController; import BlueTurtle.gui.GUIController.ASAT; ProjectInfoFinder.getClassPackage().clear(); } /** * Test that the user direction path is the same. */ @Test public void testUserDir() { String expected = userDir; String actual = JavaController.getUserDir(); assertEquals(expected, actual); } /** * Test that all files are null at first. */ @Test public void allFilesStringsAreNull() { assertTrue(JavaController.getCheckStyleOutputFiles() == null && JavaController.getPmdOutputFiles() == null && JavaController.getFindBugsOutputFiles() == null); } /** * Test changing CheckStyle list of output file. */ @Test public void testChangingCheckStyleOutputFile() { ArrayList<String> list = JavaController.getCheckStyleOutputFiles(); ArrayList<String> newList = new ArrayList<String>(); newList.add("test path for checkstyle");
JavaController.setASATOutputFiles(ASAT.CheckStyle, newList);
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/writers/JSWriter.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // }
import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import BlueTurtle.gui.GUIController; import BlueTurtle.summarizers.Summarizer; import BlueTurtle.uav.CodeFile; import lombok.Getter; import lombok.Setter;
package BlueTurtle.writers; /** * This class can be used to write the output of the analyzer to JavaScript * format. * * @author BlueTurtle. * */ @SuppressWarnings("checkstyle:nowhitespacebefore") public final class JSWriter { private static JSWriter jsWriter = null; @Getter @Setter private List<Summarizer> summarizedWarnings; /** * Constructor. Only this class can instantiate itself. */ private JSWriter() { } /** * Get an instance of this class. * * @return an instance of this class. */ public static synchronized JSWriter getInstance() { if (jsWriter == null) { jsWriter = new JSWriter(); } return jsWriter; } /** * Write the summarized warnings to a file in JavaScript format. * * @param outputFilePath * path to write the output to. * @throws IOException * throws an exception if something went wrong in the process of * writing to file. */ public void writeToJSFormat(String outputFilePath) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath)); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(summarizedWarnings) + ';'; writer.write("var inputData = "); writer.newLine(); writer.write(json); writer.newLine();
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public class GUIController { // // // /** // * Enums to represent the ASATs. // * // * @author BlueTurtle. // * // */ // public enum ASAT { CheckStyle, PMD, FindBugs; } // // @FXML // ResourceBundle that was given to the FXMLLoader // private ResourceBundle resources; //NOPMD - needed for the FXMLLoader. // // @FXML // URL location of the FXML file that was given to the FXMLLoader // private URL location; //NOPMD - needed for the FXMLLoader. // // @FXML // fx:id="selectButton" // private Button selectButton; // Value injected by FXMLLoader // // @FXML // fx:id="projectSourcePathText" // private Text projectSourcePathText; // Value injected by FXMLLoader // // @FXML // fx:id="visualizeButton" // private Button visualizeButton; // Value injected by FXMLLoader // // @Getter @Setter private static String projectPath; //NOPMD - warning caused by lombok. // // /** // * Event for CheckStyle button. // * // * @param event // * the event. // */ // @FXML // void selectCheckStyleConfigEvent(MouseEvent event) { } // // /** // * Event for PMD button. // * // * @param event // * the event. // */ // @FXML // void selectPMDConfigEvent(MouseEvent event) { } // // /** // * Event for FindBugs button. // * // * @param event // * the event. // */ // @FXML // void selectFindBugsConfigEvent(MouseEvent event) { } // // /** // * Events for the LoadButton. // * // * @param event // * the event. // */ // @FXML // void selectButtonEvent(MouseEvent event) { } // // /** // * Events from the VisualizeButton. // * // * @param event // * the event. // */ // @FXML // void visualizeButtonEvent(MouseEvent event) { } // // /** // * Initialize the buttons. // */ // @FXML // void initialize() { // assert visualizeButton != null : "fx:id=\"visualizeButton\" was not injected: check your FXML file 'Menu.fxml'."; // assert projectSourcePathText != null : "fx:id=\"projectSourcePathText\" was not injected: check your FXML file 'Menu.fxml'."; // assert selectButton != null : "fx:id=\"selectButton\" was not injected: check your FXML file 'Menu.fxml'."; // // // Set the event handlers for the buttons. // selectButton.setOnMouseClicked(new SelectButtonEventHandler(projectSourcePathText, visualizeButton)); // visualizeButton.setOnMouseClicked(new VisualizeButtonEventHandler()); // } // // } // Path: src/main/java/BlueTurtle/writers/JSWriter.java import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import BlueTurtle.gui.GUIController; import BlueTurtle.summarizers.Summarizer; import BlueTurtle.uav.CodeFile; import lombok.Getter; import lombok.Setter; package BlueTurtle.writers; /** * This class can be used to write the output of the analyzer to JavaScript * format. * * @author BlueTurtle. * */ @SuppressWarnings("checkstyle:nowhitespacebefore") public final class JSWriter { private static JSWriter jsWriter = null; @Getter @Setter private List<Summarizer> summarizedWarnings; /** * Constructor. Only this class can instantiate itself. */ private JSWriter() { } /** * Get an instance of this class. * * @return an instance of this class. */ public static synchronized JSWriter getInstance() { if (jsWriter == null) { jsWriter = new JSWriter(); } return jsWriter; } /** * Write the summarized warnings to a file in JavaScript format. * * @param outputFilePath * path to write the output to. * @throws IOException * throws an exception if something went wrong in the process of * writing to file. */ public void writeToJSFormat(String outputFilePath) throws IOException { BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath)); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String json = gson.toJson(summarizedWarnings) + ';'; writer.write("var inputData = "); writer.newLine(); writer.write(json); writer.newLine();
writer.write("var projectName = " + '"' + GUIController.getProjectPath().substring(
ClintonCao/UnifiedASATVisualizer
src/test/java/BlueTurtle/summarizers/PackageSummarizerTest.java
// Path: src/main/java/BlueTurtle/warnings/CheckStyleWarning.java // public class CheckStyleWarning extends Warning { // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public CheckStyleWarning(String filePath, String filename, int line, String message, String ruleName, String classification) { // super(filePath, filename, line, "CheckStyle", ruleName, message, classification); // setMessage(message.replaceAll("'", "")); // } // // /** // * Check whether two CheckStyle warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof CheckStyleWarning)) { // return false; // } // // CheckStyleWarning that = (CheckStyleWarning) other; // // // fixed SimplifyBooleanReturn, Conditional logic can be removed. // return (ruleName.equals(that.ruleName) && filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && classification.equals(that.classification) && type.equals(that.type)); // // } // // /** // * HashCode for the CheckStyle Warning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, ruleName, classification); // } // // /** // * toString method for CheckStylWarning. // */ // @Override // public String toString() { // return "CheckStyleWarning [line=" + line + ", message=" + message + ", classification=" + classification // + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath + ", ruleName=" + ruleName // + "]"; // } // // }
import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.CheckStyleWarning; import BlueTurtle.warnings.Warning;
package BlueTurtle.summarizers; /** * Test for the PackageSummarizer class. * * @author BlueTurtle. * */ public class PackageSummarizerTest { private String packageName; private List<Warning> warningList; private Warning w; private List<Warning> warningList2; private Warning w2; private String filePath; private String filePath2; /** * Initialize necessary objects. * * @throws IOException * throws an exception if problem was encountered while reading * files. */ @Before public void initialize() throws IOException { ProjectInfoFinder pif = new ProjectInfoFinder(); pif.findFiles(new File(System.getProperty("user.dir") + "/src/test/resources")); filePath = ProjectInfoFinder.getClassPaths().stream().filter(path -> path.endsWith( "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ExampleClass.java")) .findFirst().get(); filePath2 = ProjectInfoFinder.getClassPaths().stream().filter(path -> path.endsWith("src" + File.separator + "test" + File.separator + "resources" + File.separator + "ExampleTestClass.java")).findFirst().get(); packageName = "SomePackage.subpackage";
// Path: src/main/java/BlueTurtle/warnings/CheckStyleWarning.java // public class CheckStyleWarning extends Warning { // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public CheckStyleWarning(String filePath, String filename, int line, String message, String ruleName, String classification) { // super(filePath, filename, line, "CheckStyle", ruleName, message, classification); // setMessage(message.replaceAll("'", "")); // } // // /** // * Check whether two CheckStyle warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof CheckStyleWarning)) { // return false; // } // // CheckStyleWarning that = (CheckStyleWarning) other; // // // fixed SimplifyBooleanReturn, Conditional logic can be removed. // return (ruleName.equals(that.ruleName) && filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && classification.equals(that.classification) && type.equals(that.type)); // // } // // /** // * HashCode for the CheckStyle Warning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, ruleName, classification); // } // // /** // * toString method for CheckStylWarning. // */ // @Override // public String toString() { // return "CheckStyleWarning [line=" + line + ", message=" + message + ", classification=" + classification // + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath + ", ruleName=" + ruleName // + "]"; // } // // } // Path: src/test/java/BlueTurtle/summarizers/PackageSummarizerTest.java import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.CheckStyleWarning; import BlueTurtle.warnings.Warning; package BlueTurtle.summarizers; /** * Test for the PackageSummarizer class. * * @author BlueTurtle. * */ public class PackageSummarizerTest { private String packageName; private List<Warning> warningList; private Warning w; private List<Warning> warningList2; private Warning w2; private String filePath; private String filePath2; /** * Initialize necessary objects. * * @throws IOException * throws an exception if problem was encountered while reading * files. */ @Before public void initialize() throws IOException { ProjectInfoFinder pif = new ProjectInfoFinder(); pif.findFiles(new File(System.getProperty("user.dir") + "/src/test/resources")); filePath = ProjectInfoFinder.getClassPaths().stream().filter(path -> path.endsWith( "src" + File.separator + "test" + File.separator + "resources" + File.separator + "ExampleClass.java")) .findFirst().get(); filePath2 = ProjectInfoFinder.getClassPaths().stream().filter(path -> path.endsWith("src" + File.separator + "test" + File.separator + "resources" + File.separator + "ExampleTestClass.java")).findFirst().get(); packageName = "SomePackage.subpackage";
w = new CheckStyleWarning(filePath, "ExampleClass.java", 3, "Test", "TestRule", "Class");
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/gui/GUIController.java
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // // Path: src/main/java/BlueTurtle/uav/JavaController.java // public class JavaController implements Controller { // // @Getter @Setter private static String userDir = System.getProperty("user.dir"); //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> checkStyleOutputFiles; //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> pmdOutputFiles; //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> findBugsOutputFiles; //NOPMD - caused by lombok. // // /** // * Execute controller. A command is constructed for every ASAT which needs // * to be run. // * // * @throws IOException // * throws an exception if a problem is encountered when // * executing the commands. // */ // public void execute() throws IOException { // new JSONFormatter().format(); // } // // /** // * Set the output paths for the ASAT. // * // * @param asat // * the ASAT type. // * @param filePaths // * the list of output file paths. // */ // public static void setASATOutputFiles(ASAT asat, ArrayList<String> filePaths) { // if (filePaths == null) { // return; // } // switch (asat) { // case PMD: // pmdOutputFiles = filePaths; // break; // case CheckStyle: // checkStyleOutputFiles = filePaths; // break; // case FindBugs: // findBugsOutputFiles = filePaths; // break; // default: // break; // } // } // }
import java.awt.Desktop; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController.ASAT; import BlueTurtle.uav.JavaController; import BlueTurtle.uav.Main; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import lombok.Getter; import lombok.Setter;
@Override public void handle(MouseEvent event) { try { Alert alert = alertCreator.createAlert(AlertType.INFORMATION, "info", "Collecting the data may take a few minutes for large projects."); alert.showAndWait(); findProjectInfo(); Main.runVisualization(); Desktop.getDesktop().browse(new File("visualization/main.html").toURI()); ProjectInfoFinder.cleanup(); } catch (IOException e) { e.printStackTrace(); } } /** * Find all necessary information of the project. * @throws IOException * throws an exception if a problem is encountered while reading the files. */ public void findProjectInfo() throws IOException { ProjectInfoFinder pif = new ProjectInfoFinder(); pif.findFiles(new File(GUIController.getProjectPath())); setListOfOutputFiles(); pif.retrieveCodeFiles(); } /** * Set the list of output files (generated by Maven) for each ASAT. */ public void setListOfOutputFiles() {
// Path: src/main/java/BlueTurtle/gui/GUIController.java // public enum ASAT { CheckStyle, PMD, FindBugs; } // // Path: src/main/java/BlueTurtle/uav/JavaController.java // public class JavaController implements Controller { // // @Getter @Setter private static String userDir = System.getProperty("user.dir"); //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> checkStyleOutputFiles; //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> pmdOutputFiles; //NOPMD - caused by lombok. // @Getter @Setter private static ArrayList<String> findBugsOutputFiles; //NOPMD - caused by lombok. // // /** // * Execute controller. A command is constructed for every ASAT which needs // * to be run. // * // * @throws IOException // * throws an exception if a problem is encountered when // * executing the commands. // */ // public void execute() throws IOException { // new JSONFormatter().format(); // } // // /** // * Set the output paths for the ASAT. // * // * @param asat // * the ASAT type. // * @param filePaths // * the list of output file paths. // */ // public static void setASATOutputFiles(ASAT asat, ArrayList<String> filePaths) { // if (filePaths == null) { // return; // } // switch (asat) { // case PMD: // pmdOutputFiles = filePaths; // break; // case CheckStyle: // checkStyleOutputFiles = filePaths; // break; // case FindBugs: // findBugsOutputFiles = filePaths; // break; // default: // break; // } // } // } // Path: src/main/java/BlueTurtle/gui/GUIController.java import java.awt.Desktop; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.gui.GUIController.ASAT; import BlueTurtle.uav.JavaController; import BlueTurtle.uav.Main; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.text.Text; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import lombok.Getter; import lombok.Setter; @Override public void handle(MouseEvent event) { try { Alert alert = alertCreator.createAlert(AlertType.INFORMATION, "info", "Collecting the data may take a few minutes for large projects."); alert.showAndWait(); findProjectInfo(); Main.runVisualization(); Desktop.getDesktop().browse(new File("visualization/main.html").toURI()); ProjectInfoFinder.cleanup(); } catch (IOException e) { e.printStackTrace(); } } /** * Find all necessary information of the project. * @throws IOException * throws an exception if a problem is encountered while reading the files. */ public void findProjectInfo() throws IOException { ProjectInfoFinder pif = new ProjectInfoFinder(); pif.findFiles(new File(GUIController.getProjectPath())); setListOfOutputFiles(); pif.retrieveCodeFiles(); } /** * Set the list of output files (generated by Maven) for each ASAT. */ public void setListOfOutputFiles() {
JavaController.setASATOutputFiles(ASAT.CheckStyle, ProjectInfoFinder.getOutputFilesPaths().get(ASAT.CheckStyle));
ClintonCao/UnifiedASATVisualizer
src/test/java/BlueTurtle/parsers/FindBugsXMLParserTest.java
// Path: src/main/java/BlueTurtle/warnings/FindBugsWarning.java // public class FindBugsWarning extends Warning { // // // @Getter @Setter private String category; // @Getter @Setter private String priority; // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * @param category // * the category of the warning. // * @param priority // * the priority of the warning. // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public FindBugsWarning(String filePath, String filename, int line, String message, String category, String priority, String ruleName, String classification) { // super(filePath, filename, line, "FindBugs", ruleName, message, classification); // setCategory(category); // setPriority(priority); // } // // // /** // * Check whether two FindBugs warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof FindBugsWarning)) { // return false; // } // // FindBugsWarning that = (FindBugsWarning) other; // // return (filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && category.equals(that.category) && classification.equals(that.classification) // && priority.equals(that.priority) && type.equals(that.type) && ruleName.equals(that.ruleName)); // } // // /** // * HashCode for the FindBugsWarning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, category, priority, ruleName, classification); // } // // /** // * toString method for FindBugsWarning. // */ // @Override // public String toString() { // return "FindBugsWarning [lineNumber=" + line + ", message=" + message + ", category=" + category // + ", priority=" + priority + ", classification=" // + classification + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath // + ", ruleName=" + ruleName + "]"; // } // // }
import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.FindBugsWarning; import BlueTurtle.warnings.Warning;
* Clear the attributes of ProjectInfoFinder. */ @After public void tearDown() { ProjectInfoFinder.getClassLocs().clear(); ProjectInfoFinder.getClassPackage().clear(); ProjectInfoFinder.getClassPaths().clear(); ProjectInfoFinder.getPackages().clear(); } /** * Test that the parser can parse a valid FindBugs output file. */ @Test public void testParseCorrectBehaviour() { FindBugsXMLParser parser = new FindBugsXMLParser(); List<Warning> warnings = parser.parseFile(testSet2); assertSame(2, warnings.size()); } /** * Test whether the parser creates the right object. */ @Test public void testParsingOneWarning() { FindBugsXMLParser parser = new FindBugsXMLParser();
// Path: src/main/java/BlueTurtle/warnings/FindBugsWarning.java // public class FindBugsWarning extends Warning { // // // @Getter @Setter private String category; // @Getter @Setter private String priority; // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * @param category // * the category of the warning. // * @param priority // * the priority of the warning. // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public FindBugsWarning(String filePath, String filename, int line, String message, String category, String priority, String ruleName, String classification) { // super(filePath, filename, line, "FindBugs", ruleName, message, classification); // setCategory(category); // setPriority(priority); // } // // // /** // * Check whether two FindBugs warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof FindBugsWarning)) { // return false; // } // // FindBugsWarning that = (FindBugsWarning) other; // // return (filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && category.equals(that.category) && classification.equals(that.classification) // && priority.equals(that.priority) && type.equals(that.type) && ruleName.equals(that.ruleName)); // } // // /** // * HashCode for the FindBugsWarning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, category, priority, ruleName, classification); // } // // /** // * toString method for FindBugsWarning. // */ // @Override // public String toString() { // return "FindBugsWarning [lineNumber=" + line + ", message=" + message + ", category=" + category // + ", priority=" + priority + ", classification=" // + classification + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath // + ", ruleName=" + ruleName + "]"; // } // // } // Path: src/test/java/BlueTurtle/parsers/FindBugsXMLParserTest.java import java.io.File; import java.io.IOException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertSame; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.FindBugsWarning; import BlueTurtle.warnings.Warning; * Clear the attributes of ProjectInfoFinder. */ @After public void tearDown() { ProjectInfoFinder.getClassLocs().clear(); ProjectInfoFinder.getClassPackage().clear(); ProjectInfoFinder.getClassPaths().clear(); ProjectInfoFinder.getPackages().clear(); } /** * Test that the parser can parse a valid FindBugs output file. */ @Test public void testParseCorrectBehaviour() { FindBugsXMLParser parser = new FindBugsXMLParser(); List<Warning> warnings = parser.parseFile(testSet2); assertSame(2, warnings.size()); } /** * Test whether the parser creates the right object. */ @Test public void testParsingOneWarning() { FindBugsXMLParser parser = new FindBugsXMLParser();
FindBugsWarning expected = new FindBugsWarning(testSet3FilePath, testSet2FileName, 47, testSet2Message,
ClintonCao/UnifiedASATVisualizer
src/main/java/BlueTurtle/parsers/CheckStyleXMLParser.java
// Path: src/main/java/BlueTurtle/warnings/CheckStyleWarning.java // public class CheckStyleWarning extends Warning { // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public CheckStyleWarning(String filePath, String filename, int line, String message, String ruleName, String classification) { // super(filePath, filename, line, "CheckStyle", ruleName, message, classification); // setMessage(message.replaceAll("'", "")); // } // // /** // * Check whether two CheckStyle warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof CheckStyleWarning)) { // return false; // } // // CheckStyleWarning that = (CheckStyleWarning) other; // // // fixed SimplifyBooleanReturn, Conditional logic can be removed. // return (ruleName.equals(that.ruleName) && filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && classification.equals(that.classification) && type.equals(that.type)); // // } // // /** // * HashCode for the CheckStyle Warning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, ruleName, classification); // } // // /** // * toString method for CheckStylWarning. // */ // @Override // public String toString() { // return "CheckStyleWarning [line=" + line + ", message=" + message + ", classification=" + classification // + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath + ", ruleName=" + ruleName // + "]"; // } // // }
import org.w3c.dom.NodeList; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.CheckStyleWarning; import BlueTurtle.warnings.Warning; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher;
// Convert the node to an element. Element warningElement = (Element) warning; // The message contained by the warning. String message = warningElement.getAttribute("message"); // line number where the warning is located. int line = Integer.parseInt(warningElement.getAttribute("line")); // Get the category of the warning. String ruleName = getRuleName(warningElement.getAttribute("source")); String classification = classify(ruleName); // replace the backward slash in the file name with file separator. String fileNWithSep = fileName.replaceAll("\\\\", Matcher.quoteReplacement(File.separator)); try { // for-loop in stream, find correct filePath. String filePath = ProjectInfoFinder.getClassPaths().stream().filter(p -> p.endsWith(fileNWithSep)) .findFirst().get(); // Get the name of the file where the warning is from. String finalFileName = fileNWithSep.substring(fileNWithSep.lastIndexOf(File.separatorChar) + 1, fileNWithSep.length()); // Add warning to the list of warnings. checkStyleWarnings
// Path: src/main/java/BlueTurtle/warnings/CheckStyleWarning.java // public class CheckStyleWarning extends Warning { // // // /** // * Constructor. // * // * @param filePath // * the path to the file where the warning is located. // * @param filename // * the name of the file where the warning is located. // * @param line // * the line number where the warning is located. // * @param message // * the message of the warning. // * // * @param ruleName // * the rule name of the warning. // * @param classification // * of the violated rule of the warning. // */ // public CheckStyleWarning(String filePath, String filename, int line, String message, String ruleName, String classification) { // super(filePath, filename, line, "CheckStyle", ruleName, message, classification); // setMessage(message.replaceAll("'", "")); // } // // /** // * Check whether two CheckStyle warnings are the same. // * // * @param other // * the other warning. // * @return a boolean // */ // @Override // public boolean equals(Object other) { // // if (!(other instanceof CheckStyleWarning)) { // return false; // } // // CheckStyleWarning that = (CheckStyleWarning) other; // // // fixed SimplifyBooleanReturn, Conditional logic can be removed. // return (ruleName.equals(that.ruleName) && filePath.equals(that.filePath) && fileName.equals(that.fileName) && line == that.line // && message.equals(that.message) && classification.equals(that.classification) && type.equals(that.type)); // // } // // /** // * HashCode for the CheckStyle Warning. // */ // @Override // public int hashCode() { // return java.util.Objects.hash(filePath, fileName, type, line, message, ruleName, classification); // } // // /** // * toString method for CheckStylWarning. // */ // @Override // public String toString() { // return "CheckStyleWarning [line=" + line + ", message=" + message + ", classification=" + classification // + ", fileName=" + fileName + ", type=" + type + ", filePath=" + filePath + ", ruleName=" + ruleName // + "]"; // } // // } // Path: src/main/java/BlueTurtle/parsers/CheckStyleXMLParser.java import org.w3c.dom.NodeList; import BlueTurtle.finders.ProjectInfoFinder; import BlueTurtle.warnings.CheckStyleWarning; import BlueTurtle.warnings.Warning; import org.w3c.dom.Node; import org.w3c.dom.Element; import java.io.File; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.regex.Matcher; // Convert the node to an element. Element warningElement = (Element) warning; // The message contained by the warning. String message = warningElement.getAttribute("message"); // line number where the warning is located. int line = Integer.parseInt(warningElement.getAttribute("line")); // Get the category of the warning. String ruleName = getRuleName(warningElement.getAttribute("source")); String classification = classify(ruleName); // replace the backward slash in the file name with file separator. String fileNWithSep = fileName.replaceAll("\\\\", Matcher.quoteReplacement(File.separator)); try { // for-loop in stream, find correct filePath. String filePath = ProjectInfoFinder.getClassPaths().stream().filter(p -> p.endsWith(fileNWithSep)) .findFirst().get(); // Get the name of the file where the warning is from. String finalFileName = fileNWithSep.substring(fileNWithSep.lastIndexOf(File.separatorChar) + 1, fileNWithSep.length()); // Add warning to the list of warnings. checkStyleWarnings
.add(new CheckStyleWarning(filePath, finalFileName, line, message, ruleName, classification));
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // }
import java.util.ArrayList; import java.util.List; import ayaseruri.torr.torrfm.objectholder.LrcInfo;
package ayaseruri.torr.torrfm.model; /** * Created by ayaseruri on 15/12/12. */ public class LrcModel { private int indexCurrent; private List<ILrc> iLrcs;
// Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java import java.util.ArrayList; import java.util.List; import ayaseruri.torr.torrfm.objectholder.LrcInfo; package ayaseruri.torr.torrfm.model; /** * Created by ayaseruri on 15/12/12. */ public class LrcModel { private int indexCurrent; private List<ILrc> iLrcs;
private ArrayList<LrcInfo> lrcInfos;
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/controller/LrcController.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // }
import java.util.ArrayList; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo;
package ayaseruri.torr.torrfm.controller; /** * Created by ayaseruri on 15/12/20. */ public class LrcController { private LrcModel lrcModel; public LrcController(LrcModel lrcModel) { this.lrcModel = lrcModel; } public void setMusicTimeCurrent(long currentTime){ for(int i=0; i< lrcModel.getLrcInfos().size(); i++){ if(i + 1 < lrcModel.getLrcInfos().size()){ if(lrcModel.getLrcInfos().get(i).getTime() < currentTime && lrcModel.getLrcInfos().get(i + 1).getTime() > currentTime){ lrcModel.setIndexCurrent(i); } }else { if(lrcModel.getLrcInfos().get(i).getTime() < currentTime){ lrcModel.setIndexCurrent(i); } } } } public void reset(){
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/controller/LrcController.java import java.util.ArrayList; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo; package ayaseruri.torr.torrfm.controller; /** * Created by ayaseruri on 15/12/20. */ public class LrcController { private LrcModel lrcModel; public LrcController(LrcModel lrcModel) { this.lrcModel = lrcModel; } public void setMusicTimeCurrent(long currentTime){ for(int i=0; i< lrcModel.getLrcInfos().size(); i++){ if(i + 1 < lrcModel.getLrcInfos().size()){ if(lrcModel.getLrcInfos().get(i).getTime() < currentTime && lrcModel.getLrcInfos().get(i + 1).getTime() > currentTime){ lrcModel.setIndexCurrent(i); } }else { if(lrcModel.getLrcInfos().get(i).getTime() < currentTime){ lrcModel.setIndexCurrent(i); } } } } public void reset(){
lrcModel.setLrcInfos(new ArrayList<LrcInfo>());
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/view/LrcView.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // }
import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; import java.util.ArrayList; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo;
package ayaseruri.torr.torrfm.view; /** * Created by ayaseruri on 15/12/13. */ public class LrcView extends TextView { private Paint currentPaint; private Paint notCurrentPaint; private int currentColor, noCurrentColor; private float currentSize, noCurrentSize, lineSpace;
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/view/LrcView.java import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; import java.util.ArrayList; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo; package ayaseruri.torr.torrfm.view; /** * Created by ayaseruri on 15/12/13. */ public class LrcView extends TextView { private Paint currentPaint; private Paint notCurrentPaint; private int currentColor, noCurrentColor; private float currentSize, noCurrentSize, lineSpace;
private LrcModel lrcModel;
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/view/LrcView.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // }
import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; import java.util.ArrayList; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo;
public LrcView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LrcView); currentColor = array.getColor(R.styleable.LrcView_currentColor , getResources().getColor(android.R.color.white)); noCurrentColor = array.getColor(R.styleable.LrcView_noCurrentColor , getResources().getColor(R.color.colorAccent)); currentSize = array.getDimension(R.styleable.LrcView_currentSize, 12.0f); noCurrentSize = array.getDimension(R.styleable.LrcView_noCurrentSize, 12.0f); lineSpace = array.getDimension(R.styleable.LrcView_lineSpace, 12.0f); array.recycle(); currentPaint = new Paint(); currentPaint.setAntiAlias(true); currentPaint.setTextSize(currentSize); currentPaint.setTextAlign(Paint.Align.CENTER); currentPaint.setColor(currentColor); notCurrentPaint = new Paint(); notCurrentPaint.setAntiAlias(true); notCurrentPaint.setTextSize(noCurrentSize); notCurrentPaint.setTextAlign(Paint.Align.CENTER); notCurrentPaint.setColor(noCurrentColor); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas);
// Path: app/src/main/java/ayaseruri/torr/torrfm/model/LrcModel.java // public class LrcModel { // private int indexCurrent; // private List<ILrc> iLrcs; // private ArrayList<LrcInfo> lrcInfos; // // public LrcModel() { // indexCurrent = 0; // lrcInfos = new ArrayList<>(); // iLrcs = new ArrayList<>(); // } // // public void addILrc(ILrc iLrc) { // this.iLrcs.add(iLrc); // } // // public int getIndexCurrent() { // return indexCurrent; // } // // public void setIndexCurrent(int indexCurrent) { // this.indexCurrent = indexCurrent; // update(); // } // // public void setLrcInfos(ArrayList<LrcInfo> lrcInfos) { // this.lrcInfos = lrcInfos; // update(); // } // // public ArrayList<LrcInfo> getLrcInfos() { // return lrcInfos; // } // // private void update() { // for (ILrc iLrc : iLrcs) { // iLrc.onLrcUpdate(this); // } // } // // public interface ILrc { // void onLrcUpdate(LrcModel lrcModel); // } // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/view/LrcView.java import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.TextView; import java.util.ArrayList; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.model.LrcModel; import ayaseruri.torr.torrfm.objectholder.LrcInfo; public LrcView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.LrcView); currentColor = array.getColor(R.styleable.LrcView_currentColor , getResources().getColor(android.R.color.white)); noCurrentColor = array.getColor(R.styleable.LrcView_noCurrentColor , getResources().getColor(R.color.colorAccent)); currentSize = array.getDimension(R.styleable.LrcView_currentSize, 12.0f); noCurrentSize = array.getDimension(R.styleable.LrcView_noCurrentSize, 12.0f); lineSpace = array.getDimension(R.styleable.LrcView_lineSpace, 12.0f); array.recycle(); currentPaint = new Paint(); currentPaint.setAntiAlias(true); currentPaint.setTextSize(currentSize); currentPaint.setTextAlign(Paint.Align.CENTER); currentPaint.setColor(currentColor); notCurrentPaint = new Paint(); notCurrentPaint.setAntiAlias(true); notCurrentPaint.setTextSize(noCurrentSize); notCurrentPaint.setTextAlign(Paint.Align.CENTER); notCurrentPaint.setColor(noCurrentColor); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas);
ArrayList<LrcInfo> lrcs = lrcModel.getLrcInfos();
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/utils/Util.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // }
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import ayaseruri.torr.torrfm.objectholder.LrcInfo;
package ayaseruri.torr.torrfm.utils; /** * Created by ayaseruri on 15/12/12. */ public class Util { private static final Pattern lrclineFormate = Pattern.compile("^\\[.+\\].{0,}$", Pattern.MULTILINE); private static final Pattern lrcTimeFormate = Pattern.compile("\\[\\d+[.:]\\d+[.:]\\d+\\]"); public static String FormatMusicTime(int ms) { Date date = new Date(ms); return new SimpleDateFormat("mm:ss").format(date); }
// Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/LrcInfo.java // public class LrcInfo { // private long time; // private String jp; // private String cn; // // public LrcInfo(long time, String jp, String cn) { // this.time = time; // this.jp = jp; // this.cn = cn; // } // // public long getTime() { // return time; // } // // public String getJp() { // return jp; // } // // public String getCn() { // return cn; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/utils/Util.java import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import ayaseruri.torr.torrfm.objectholder.LrcInfo; package ayaseruri.torr.torrfm.utils; /** * Created by ayaseruri on 15/12/12. */ public class Util { private static final Pattern lrclineFormate = Pattern.compile("^\\[.+\\].{0,}$", Pattern.MULTILINE); private static final Pattern lrcTimeFormate = Pattern.compile("\\[\\d+[.:]\\d+[.:]\\d+\\]"); public static String FormatMusicTime(int ms) { Date date = new Date(ms); return new SimpleDateFormat("mm:ss").format(date); }
public static ArrayList<LrcInfo> decodeLrc(String rawString) throws Exception {
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // }
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers;
package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo);
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo);
RetrofitClient.apiService.getOneSentence("http://api.hitokoto.us/rand?&cat=a")
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // }
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers;
package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo); RetrofitClient.apiService.getOneSentence("http://api.hitokoto.us/rand?&cat=a")
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo); RetrofitClient.apiService.getOneSentence("http://api.hitokoto.us/rand?&cat=a")
.subscribeOn(Schedulers.from(Constant.executor))
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // }
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers;
package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo); RetrofitClient.apiService.getOneSentence("http://api.hitokoto.us/rand?&cat=a") .subscribeOn(Schedulers.from(Constant.executor)) .observeOn(AndroidSchedulers.mainThread())
// Path: app/src/main/java/ayaseruri/torr/torrfm/global/Constant.java // public class Constant { // public static ExecutorService executor = Executors.newFixedThreadPool(6); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/objectholder/OneSentenceInfo.java // public class OneSentenceInfo { // // /** // * hitokoto : 我想要握紧的并不是匕首或是什么,只不过是他的掌心而已。 // * cat : a // * author : 万事屋神乐酱 // * source : 空之境界 // * like : 10 // * date : 2011.11.24 19:26:59 // * catname : Anime - 动画 // * id : 1322134019000 // */ // // private String hitokoto; // private String cat; // private String author; // private String source; // private int like; // private String date; // private String catname; // private long id; // // public String getHitokoto() { // return hitokoto; // } // // public void setHitokoto(String hitokoto) { // this.hitokoto = hitokoto; // } // // public String getCat() { // return cat; // } // // public void setCat(String cat) { // this.cat = cat; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getSource() { // return source; // } // // public void setSource(String source) { // this.source = source; // } // // public int getLike() { // return like; // } // // public void setLike(int like) { // this.like = like; // } // // public String getDate() { // return date; // } // // public void setDate(String date) { // this.date = date; // } // // public String getCatname() { // return catname; // } // // public void setCatname(String catname) { // this.catname = catname; // } // // public long getId() { // return id; // } // // public void setId(long id) { // this.id = id; // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/activity/StartActivity.java import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.daimajia.androidanimations.library.Techniques; import com.daimajia.androidanimations.library.YoYo; import com.nineoldandroids.animation.Animator; import com.nineoldandroids.animation.AnimatorListenerAdapter; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.EActivity; import org.androidannotations.annotations.UiThread; import org.androidannotations.annotations.ViewById; import ayaseruri.torr.torrfm.R; import ayaseruri.torr.torrfm.global.Constant; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.objectholder.OneSentenceInfo; import rx.android.schedulers.AndroidSchedulers; import rx.functions.Action1; import rx.schedulers.Schedulers; package ayaseruri.torr.torrfm.activity; @EActivity(R.layout.activity_start) public class StartActivity extends AppCompatActivity { private static final int DURATION = 3000; @ViewById(R.id.logo) ImageView logo; @ViewById(R.id.one_sentence) TextView oneSentence; @AfterViews void init() { YoYo.with(Techniques.DropOut).duration(DURATION).withListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { // startMain(); } }).playOn(logo); RetrofitClient.apiService.getOneSentence("http://api.hitokoto.us/rand?&cat=a") .subscribeOn(Schedulers.from(Constant.executor)) .observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<OneSentenceInfo>() {
ayaseruri/TorrFM
app/src/main/java/ayaseruri/torr/torrfm/global/MApplication.java
// Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/utils/LocalDisplay.java // public class LocalDisplay { // // public static int SCREEN_WIDTH_PIXELS; // public static int SCREEN_HEIGHT_PIXELS; // public static float SCREEN_DENSITY; // public static int SCREEN_WIDTH_DP; // public static int SCREEN_HEIGHT_DP; // // public static void init(Context context) { // // DisplayMetrics dm = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // wm.getDefaultDisplay().getMetrics(dm); // SCREEN_WIDTH_PIXELS = dm.widthPixels; // SCREEN_HEIGHT_PIXELS = dm.heightPixels; // SCREEN_DENSITY = dm.density; // SCREEN_WIDTH_DP = (int) (SCREEN_WIDTH_PIXELS / dm.density); // SCREEN_HEIGHT_DP = (int) (SCREEN_HEIGHT_PIXELS / dm.density); // } // // public static int dp2px(float dp) { // final float scale = SCREEN_DENSITY; // return (int) (dp * scale + 0.5f); // } // // public static int designedDP2px(float designedDp) { // if (SCREEN_WIDTH_DP != 320) { // designedDp = designedDp * SCREEN_WIDTH_DP / 320f; // } // return dp2px(designedDp); // } // // public static void setPadding(final View view, float left, float top, float right, float bottom) { // view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right), dp2px(bottom)); // } // }
import android.app.Application; import android.content.res.Resources; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipelineConfig; import org.androidannotations.annotations.EApplication; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.utils.LocalDisplay;
package ayaseruri.torr.torrfm.global; /** * Created by ayaseruri on 15/12/11. */ @EApplication public class MApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this);
// Path: app/src/main/java/ayaseruri/torr/torrfm/network/RetrofitClient.java // public class RetrofitClient { // public static ApiService apiService = new Retrofit.Builder() // .baseUrl("http://danmu.fm/") // .addConverterFactory(new FastJsonConverter()) // .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // .build() // .create(ApiService.class); // public static OkHttpClient okHttpClient = new OkHttpClient(); // } // // Path: app/src/main/java/ayaseruri/torr/torrfm/utils/LocalDisplay.java // public class LocalDisplay { // // public static int SCREEN_WIDTH_PIXELS; // public static int SCREEN_HEIGHT_PIXELS; // public static float SCREEN_DENSITY; // public static int SCREEN_WIDTH_DP; // public static int SCREEN_HEIGHT_DP; // // public static void init(Context context) { // // DisplayMetrics dm = new DisplayMetrics(); // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); // wm.getDefaultDisplay().getMetrics(dm); // SCREEN_WIDTH_PIXELS = dm.widthPixels; // SCREEN_HEIGHT_PIXELS = dm.heightPixels; // SCREEN_DENSITY = dm.density; // SCREEN_WIDTH_DP = (int) (SCREEN_WIDTH_PIXELS / dm.density); // SCREEN_HEIGHT_DP = (int) (SCREEN_HEIGHT_PIXELS / dm.density); // } // // public static int dp2px(float dp) { // final float scale = SCREEN_DENSITY; // return (int) (dp * scale + 0.5f); // } // // public static int designedDP2px(float designedDp) { // if (SCREEN_WIDTH_DP != 320) { // designedDp = designedDp * SCREEN_WIDTH_DP / 320f; // } // return dp2px(designedDp); // } // // public static void setPadding(final View view, float left, float top, float right, float bottom) { // view.setPadding(designedDP2px(left), dp2px(top), designedDP2px(right), dp2px(bottom)); // } // } // Path: app/src/main/java/ayaseruri/torr/torrfm/global/MApplication.java import android.app.Application; import android.content.res.Resources; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.imagepipeline.core.ImagePipelineConfig; import org.androidannotations.annotations.EApplication; import ayaseruri.torr.torrfm.network.RetrofitClient; import ayaseruri.torr.torrfm.utils.LocalDisplay; package ayaseruri.torr.torrfm.global; /** * Created by ayaseruri on 15/12/11. */ @EApplication public class MApplication extends Application { @Override public void onCreate() { super.onCreate(); Fresco.initialize(this);
LocalDisplay.init(this);
edwise/complete-spring-project
src/test/java/com/edwise/completespring/entities/BookTest.java
// Path: src/test/java/com/edwise/completespring/testutil/BookBuilder.java // public class BookBuilder { // // private final Book book; // // public BookBuilder() { // book = new Book(); // } // // public BookBuilder id(Long id) { // book.setId(id); // return this; // } // // public BookBuilder title(String title) { // book.setTitle(title); // return this; // } // // public BookBuilder authors(List<Author> authors) { // book.setAuthors(authors); // return this; // } // // public BookBuilder isbn(String isbn) { // book.setIsbn(isbn); // return this; // } // // public BookBuilder releaseDate(LocalDate releaseDate) { // book.setReleaseDate(releaseDate); // return this; // } // // public BookBuilder publisher(Publisher publisher) { // book.setPublisher(publisher); // return this; // } // // public Book build() { // return book; // } // }
import com.edwise.completespring.testutil.BookBuilder; import org.junit.Test; import java.time.LocalDate; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat;
package com.edwise.completespring.entities; public class BookTest { private static final long BOOK_ID_TEST1 = 31L; private static final String BOOK_TITLE_TEST1 = "Lord of the Rings"; private static final String BOOK_TITLE_TEST2 = "Bautismo de Fuego"; private static final String AUTHOR_NAME_TEST1 = "J.R.R."; private static final String AUTHOR_SURNAME_TEST1 = "Tolkien"; private static final String BOOK_ISBN_TEST1 = "11-333-12"; private static final String BOOK_ISBN_TEST2 = "21-929-34"; private static final String PUBLISHER_NAME_TEST1 = "Editorial Planeta"; private static final String PUBLISHER_NAME_TEST2 = "Gigamesh"; private static final String PUBLISHER_COUNTRY_TEST1 = "ES"; private static final LocalDate DATE_TEST1 = LocalDate.of(2013, 1, 26); @Test public void testCopyFrom() {
// Path: src/test/java/com/edwise/completespring/testutil/BookBuilder.java // public class BookBuilder { // // private final Book book; // // public BookBuilder() { // book = new Book(); // } // // public BookBuilder id(Long id) { // book.setId(id); // return this; // } // // public BookBuilder title(String title) { // book.setTitle(title); // return this; // } // // public BookBuilder authors(List<Author> authors) { // book.setAuthors(authors); // return this; // } // // public BookBuilder isbn(String isbn) { // book.setIsbn(isbn); // return this; // } // // public BookBuilder releaseDate(LocalDate releaseDate) { // book.setReleaseDate(releaseDate); // return this; // } // // public BookBuilder publisher(Publisher publisher) { // book.setPublisher(publisher); // return this; // } // // public Book build() { // return book; // } // } // Path: src/test/java/com/edwise/completespring/entities/BookTest.java import com.edwise.completespring.testutil.BookBuilder; import org.junit.Test; import java.time.LocalDate; import java.util.Collections; import static org.assertj.core.api.Assertions.assertThat; package com.edwise.completespring.entities; public class BookTest { private static final long BOOK_ID_TEST1 = 31L; private static final String BOOK_TITLE_TEST1 = "Lord of the Rings"; private static final String BOOK_TITLE_TEST2 = "Bautismo de Fuego"; private static final String AUTHOR_NAME_TEST1 = "J.R.R."; private static final String AUTHOR_SURNAME_TEST1 = "Tolkien"; private static final String BOOK_ISBN_TEST1 = "11-333-12"; private static final String BOOK_ISBN_TEST2 = "21-929-34"; private static final String PUBLISHER_NAME_TEST1 = "Editorial Planeta"; private static final String PUBLISHER_NAME_TEST2 = "Gigamesh"; private static final String PUBLISHER_COUNTRY_TEST1 = "ES"; private static final LocalDate DATE_TEST1 = LocalDate.of(2013, 1, 26); @Test public void testCopyFrom() {
Book bookFrom = new BookBuilder()
edwise/complete-spring-project
src/integration-test/java/com/edwise/completespring/testswagger/ITCommonSwaggerAPITest.java
// Path: src/main/java/com/edwise/completespring/Application.java // @Slf4j // @SpringBootApplication // public class Application { // // @Autowired // private DataLoader dataLoader; // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // // @Bean // CommandLineRunner init(@Value("${db.resetAndLoadOnStartup:true}") boolean resetAndLoadDBDataOnStartup) { // return args -> initApp(resetAndLoadDBDataOnStartup); // } // // void initApp(boolean restAndLoadDBData) { // log.info("Init Application..."); // if (restAndLoadDBData) { // dataLoader.fillDBData(); // } // log.info("Aplication initiated!"); // } // // } // // Path: src/main/java/com/edwise/completespring/config/SwaggerConfig.java // @Configuration // @EnableSwagger2 // public class SwaggerConfig { // public static final String BOOKS_API_GROUP = "books-api"; // // @Bean // public Docket newsApi() { // return new Docket(DocumentationType.SWAGGER_2) // .groupName(BOOKS_API_GROUP) // .apiInfo(apiInfo()) // .directModelSubstitute(LocalDate.class, String.class) // .select() // .paths(regex("/api.*")) // .build(); // } // // private ApiInfo apiInfo() { // return new ApiInfoBuilder() // .title("Books API") // .description("Your book database!") // .termsOfServiceUrl("http://en.wikipedia.org/wiki/Terms_of_service") // .contact(new Contact("edwise", "https://github.com/edwise", "edwise.null@gmail.com")) // .license("Apache License Version 2.0") // .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") // .version("2.0") // .build(); // } // }
import com.edwise.completespring.Application; import com.edwise.completespring.config.SwaggerConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package com.edwise.completespring.testswagger; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class ITCommonSwaggerAPITest { private MockMvc mockMvc; @Autowired protected WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); } @Test public void getApiDocsSwagger_shouldReturnGeneralInfoOfAPI() throws Exception {
// Path: src/main/java/com/edwise/completespring/Application.java // @Slf4j // @SpringBootApplication // public class Application { // // @Autowired // private DataLoader dataLoader; // // public static void main(String[] args) { // SpringApplication.run(Application.class, args); // } // // @Bean // CommandLineRunner init(@Value("${db.resetAndLoadOnStartup:true}") boolean resetAndLoadDBDataOnStartup) { // return args -> initApp(resetAndLoadDBDataOnStartup); // } // // void initApp(boolean restAndLoadDBData) { // log.info("Init Application..."); // if (restAndLoadDBData) { // dataLoader.fillDBData(); // } // log.info("Aplication initiated!"); // } // // } // // Path: src/main/java/com/edwise/completespring/config/SwaggerConfig.java // @Configuration // @EnableSwagger2 // public class SwaggerConfig { // public static final String BOOKS_API_GROUP = "books-api"; // // @Bean // public Docket newsApi() { // return new Docket(DocumentationType.SWAGGER_2) // .groupName(BOOKS_API_GROUP) // .apiInfo(apiInfo()) // .directModelSubstitute(LocalDate.class, String.class) // .select() // .paths(regex("/api.*")) // .build(); // } // // private ApiInfo apiInfo() { // return new ApiInfoBuilder() // .title("Books API") // .description("Your book database!") // .termsOfServiceUrl("http://en.wikipedia.org/wiki/Terms_of_service") // .contact(new Contact("edwise", "https://github.com/edwise", "edwise.null@gmail.com")) // .license("Apache License Version 2.0") // .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") // .version("2.0") // .build(); // } // } // Path: src/integration-test/java/com/edwise/completespring/testswagger/ITCommonSwaggerAPITest.java import com.edwise.completespring.Application; import com.edwise.completespring.config.SwaggerConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.Matchers.is; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package com.edwise.completespring.testswagger; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) public class ITCommonSwaggerAPITest { private MockMvc mockMvc; @Autowired protected WebApplicationContext webApplicationContext; @Before public void setUp() { mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); } @Test public void getApiDocsSwagger_shouldReturnGeneralInfoOfAPI() throws Exception {
mockMvc.perform(get("/v2/api-docs").param("group", SwaggerConfig.BOOKS_API_GROUP))
edwise/complete-spring-project
src/main/java/com/edwise/completespring/assemblers/FooResource.java
// Path: src/main/java/com/edwise/completespring/entities/Foo.java // @ApiModel(value = "Foo entity", description = "Complete info of a entity foo") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Foo { // // @ApiModelProperty(value = "Sample Id Attribute", required = true) // private Long id; // // @ApiModelProperty(value = "Sample Text Attribute", required = true) // @NotNull // private String sampleTextAttribute; // // @ApiModelProperty(value = "Sample Local Date Attribute", required = true, dataType = "LocalDate") // @NotNull // private LocalDate sampleLocalDateAttribute; // // public Foo copyFrom(Foo other) { // this.sampleTextAttribute = other.sampleTextAttribute; // this.sampleLocalDateAttribute = other.sampleLocalDateAttribute; // // return this; // } // }
import com.edwise.completespring.entities.Foo; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.hateoas.ResourceSupport;
package com.edwise.completespring.assemblers; @Getter @Setter @Accessors(chain = true) public class FooResource extends ResourceSupport {
// Path: src/main/java/com/edwise/completespring/entities/Foo.java // @ApiModel(value = "Foo entity", description = "Complete info of a entity foo") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Foo { // // @ApiModelProperty(value = "Sample Id Attribute", required = true) // private Long id; // // @ApiModelProperty(value = "Sample Text Attribute", required = true) // @NotNull // private String sampleTextAttribute; // // @ApiModelProperty(value = "Sample Local Date Attribute", required = true, dataType = "LocalDate") // @NotNull // private LocalDate sampleLocalDateAttribute; // // public Foo copyFrom(Foo other) { // this.sampleTextAttribute = other.sampleTextAttribute; // this.sampleLocalDateAttribute = other.sampleLocalDateAttribute; // // return this; // } // } // Path: src/main/java/com/edwise/completespring/assemblers/FooResource.java import com.edwise.completespring.entities.Foo; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.hateoas.ResourceSupport; package com.edwise.completespring.assemblers; @Getter @Setter @Accessors(chain = true) public class FooResource extends ResourceSupport {
private Foo foo;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/config/SpringWebSecurityConfig.java
// Path: src/main/java/com/edwise/completespring/entities/UserAccountType.java // public enum UserAccountType { // REST_USER, // ADMIN_USER // // }
import com.edwise.completespring.entities.UserAccountType; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
package com.edwise.completespring.config; @EnableWebSecurity @Configuration @Slf4j public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) { auth.authenticationProvider(authProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()
// Path: src/main/java/com/edwise/completespring/entities/UserAccountType.java // public enum UserAccountType { // REST_USER, // ADMIN_USER // // } // Path: src/main/java/com/edwise/completespring/config/SpringWebSecurityConfig.java import com.edwise.completespring.entities.UserAccountType; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.dao.DaoAuthenticationProvider; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; package com.edwise.completespring.config; @EnableWebSecurity @Configuration @Slf4j public class SpringWebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; @Override protected void configure(AuthenticationManagerBuilder auth) { auth.authenticationProvider(authProvider()); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests()
.antMatchers("/api/**").hasAnyRole(UserAccountType.REST_USER.toString(), UserAccountType.ADMIN_USER.toString())
edwise/complete-spring-project
src/test/java/com/edwise/completespring/testutil/BookBuilder.java
// Path: src/main/java/com/edwise/completespring/entities/Author.java // @ApiModel(value = "Author entity", description = "Complete info of a entity author") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Author { // // @ApiModelProperty(value = "The name of the author", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The surname of the author") // @NotEmpty // private String surname; // // public Author copyFrom(Author other) { // this.name = other.name; // this.surname = other.surname; // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Publisher.java // @ApiModel(value = "Publisher entity", description = "Complete info of a entity publisher") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Publisher { // // @ApiModelProperty(value = "The name of the publisher", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The country of the publisher", required = true) // private String country; // // @ApiModelProperty(value = "If the publisher is online or not", required = true) // private boolean isOnline; // // public Publisher copyFrom(Publisher other) { // this.name = other.name; // this.country = other.country; // this.isOnline = other.isOnline; // // return this; // } // }
import com.edwise.completespring.entities.Author; import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.Publisher; import java.time.LocalDate; import java.util.List;
package com.edwise.completespring.testutil; public class BookBuilder { private final Book book; public BookBuilder() { book = new Book(); } public BookBuilder id(Long id) { book.setId(id); return this; } public BookBuilder title(String title) { book.setTitle(title); return this; }
// Path: src/main/java/com/edwise/completespring/entities/Author.java // @ApiModel(value = "Author entity", description = "Complete info of a entity author") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Author { // // @ApiModelProperty(value = "The name of the author", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The surname of the author") // @NotEmpty // private String surname; // // public Author copyFrom(Author other) { // this.name = other.name; // this.surname = other.surname; // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Publisher.java // @ApiModel(value = "Publisher entity", description = "Complete info of a entity publisher") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Publisher { // // @ApiModelProperty(value = "The name of the publisher", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The country of the publisher", required = true) // private String country; // // @ApiModelProperty(value = "If the publisher is online or not", required = true) // private boolean isOnline; // // public Publisher copyFrom(Publisher other) { // this.name = other.name; // this.country = other.country; // this.isOnline = other.isOnline; // // return this; // } // } // Path: src/test/java/com/edwise/completespring/testutil/BookBuilder.java import com.edwise.completespring.entities.Author; import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.Publisher; import java.time.LocalDate; import java.util.List; package com.edwise.completespring.testutil; public class BookBuilder { private final Book book; public BookBuilder() { book = new Book(); } public BookBuilder id(Long id) { book.setId(id); return this; } public BookBuilder title(String title) { book.setTitle(title); return this; }
public BookBuilder authors(List<Author> authors) {
edwise/complete-spring-project
src/test/java/com/edwise/completespring/testutil/BookBuilder.java
// Path: src/main/java/com/edwise/completespring/entities/Author.java // @ApiModel(value = "Author entity", description = "Complete info of a entity author") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Author { // // @ApiModelProperty(value = "The name of the author", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The surname of the author") // @NotEmpty // private String surname; // // public Author copyFrom(Author other) { // this.name = other.name; // this.surname = other.surname; // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Publisher.java // @ApiModel(value = "Publisher entity", description = "Complete info of a entity publisher") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Publisher { // // @ApiModelProperty(value = "The name of the publisher", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The country of the publisher", required = true) // private String country; // // @ApiModelProperty(value = "If the publisher is online or not", required = true) // private boolean isOnline; // // public Publisher copyFrom(Publisher other) { // this.name = other.name; // this.country = other.country; // this.isOnline = other.isOnline; // // return this; // } // }
import com.edwise.completespring.entities.Author; import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.Publisher; import java.time.LocalDate; import java.util.List;
package com.edwise.completespring.testutil; public class BookBuilder { private final Book book; public BookBuilder() { book = new Book(); } public BookBuilder id(Long id) { book.setId(id); return this; } public BookBuilder title(String title) { book.setTitle(title); return this; } public BookBuilder authors(List<Author> authors) { book.setAuthors(authors); return this; } public BookBuilder isbn(String isbn) { book.setIsbn(isbn); return this; } public BookBuilder releaseDate(LocalDate releaseDate) { book.setReleaseDate(releaseDate); return this; }
// Path: src/main/java/com/edwise/completespring/entities/Author.java // @ApiModel(value = "Author entity", description = "Complete info of a entity author") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Author { // // @ApiModelProperty(value = "The name of the author", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The surname of the author") // @NotEmpty // private String surname; // // public Author copyFrom(Author other) { // this.name = other.name; // this.surname = other.surname; // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/Publisher.java // @ApiModel(value = "Publisher entity", description = "Complete info of a entity publisher") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Publisher { // // @ApiModelProperty(value = "The name of the publisher", required = true) // @NotEmpty // private String name; // // @ApiModelProperty(value = "The country of the publisher", required = true) // private String country; // // @ApiModelProperty(value = "If the publisher is online or not", required = true) // private boolean isOnline; // // public Publisher copyFrom(Publisher other) { // this.name = other.name; // this.country = other.country; // this.isOnline = other.isOnline; // // return this; // } // } // Path: src/test/java/com/edwise/completespring/testutil/BookBuilder.java import com.edwise.completespring.entities.Author; import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.Publisher; import java.time.LocalDate; import java.util.List; package com.edwise.completespring.testutil; public class BookBuilder { private final Book book; public BookBuilder() { book = new Book(); } public BookBuilder id(Long id) { book.setId(id); return this; } public BookBuilder title(String title) { book.setTitle(title); return this; } public BookBuilder authors(List<Author> authors) { book.setAuthors(authors); return this; } public BookBuilder isbn(String isbn) { book.setIsbn(isbn); return this; } public BookBuilder releaseDate(LocalDate releaseDate) { book.setReleaseDate(releaseDate); return this; }
public BookBuilder publisher(Publisher publisher) {
edwise/complete-spring-project
src/test/java/com/edwise/completespring/assemblers/BookResourceAssemblerTest.java
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // }
import com.edwise.completespring.entities.Book; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when;
package com.edwise.completespring.assemblers; @RunWith(MockitoJUnitRunner.class) public class BookResourceAssemblerTest { private static final long BOOK_ID_TEST = 1234L; @Mock
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // Path: src/test/java/com/edwise/completespring/assemblers/BookResourceAssemblerTest.java import com.edwise.completespring.entities.Book; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; package com.edwise.completespring.assemblers; @RunWith(MockitoJUnitRunner.class) public class BookResourceAssemblerTest { private static final long BOOK_ID_TEST = 1234L; @Mock
private Book book;
edwise/complete-spring-project
src/test/java/com/edwise/completespring/ApplicationTest.java
// Path: src/main/java/com/edwise/completespring/dbutils/DataLoader.java // @Slf4j // @Component // public class DataLoader { // private static final String USERACCOUNTS_COLLECTION = "users"; // private static final Long BOOKS_INITIAL_SEQUENCE = 4L; // private static final Long USERACCOUNTS_INITIAL_SEQUENCE = 3L; // public static final Long BOOK_ID_1 = 1L; // public static final Long BOOK_ID_2 = 2L; // public static final Long BOOK_ID_3 = 3L; // private static final Long BOOK_ID_4 = 4L; // private static final Long USER_ID_1 = 1L; // private static final Long USER_ID_2 = 2L; // public static final String USER = "user1"; // public static final String PASSWORD_USER = "password1"; // public static final String ADMIN = "admin"; // public static final String PASSWORD_ADMIN = "password1234"; // // @Autowired // private BookRepository bookRepository; // // @Autowired // private UserAccountRepository userAccountRepository; // // @Autowired // private SequenceIdRepository sequenceRepository; // // @Autowired // private PasswordEncoder passwordEncoder; // // public void fillDBData() { // log.info("Filling DB data..."); // fillDBUsersData(); // fillDBBooksData(); // log.info("DB filled with data."); // } // // private void fillDBUsersData() { // sequenceRepository.save(new SequenceId() // .setId(USERACCOUNTS_COLLECTION) // .setSeq(USERACCOUNTS_INITIAL_SEQUENCE) // ); // userAccountRepository.deleteAll(); // Arrays.asList( // new UserAccount() // .setId(USER_ID_1) // .setUsername(USER) // .setPassword(passwordEncoder.encode(PASSWORD_USER)) // .setUserType(UserAccountType.REST_USER), // new UserAccount() // .setId(USER_ID_2) // .setUsername(ADMIN) // .setPassword(passwordEncoder.encode(PASSWORD_ADMIN)) // .setUserType(UserAccountType.ADMIN_USER)) // .forEach(userAccountRepository::save); // } // // private void fillDBBooksData() { // sequenceRepository.save(new SequenceId() // .setId(BookServiceImpl.BOOK_COLLECTION) // .setSeq(BOOKS_INITIAL_SEQUENCE) // ); // bookRepository.deleteAll(); // Arrays.asList( // new Book() // .setId(BOOK_ID_1) // .setTitle("Libro prueba mongo") // .setAuthors(Collections.singletonList(new Author().setName("Edu").setSurname("Antón"))) // .setIsbn("11-333-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 1").setCountry("ES").setOnline(false)), // new Book() // .setId(BOOK_ID_2) // .setTitle("Libro prueba mongo 2") // .setAuthors( // Arrays.asList( // new Author().setName("Otro").setSurname("Más"), // new Author().setName("S.").setSurname("King"))) // .setIsbn("12-1234-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 4").setCountry("UK").setOnline(true)), // new Book() // .setId(BOOK_ID_3) // .setTitle("Libro prueba mongo 3") // .setAuthors(Collections.singletonList(new Author().setName("Nadie").setSurname("Nobody"))) // .setIsbn("12-9999-92") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 7").setCountry("ES").setOnline(true)), // new Book() // .setId(BOOK_ID_4) // .setTitle("Libro prueba mongo 4") // .setAuthors(Collections.singletonList(new Author().setName("Perry").setSurname("Mason"))) // .setIsbn("22-34565-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 33").setCountry("US").setOnline(true))) // .forEach(bookRepository::save); // } // }
import com.edwise.completespring.dbutils.DataLoader; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions;
package com.edwise.completespring; @RunWith(MockitoJUnitRunner.class) public class ApplicationTest { @Mock
// Path: src/main/java/com/edwise/completespring/dbutils/DataLoader.java // @Slf4j // @Component // public class DataLoader { // private static final String USERACCOUNTS_COLLECTION = "users"; // private static final Long BOOKS_INITIAL_SEQUENCE = 4L; // private static final Long USERACCOUNTS_INITIAL_SEQUENCE = 3L; // public static final Long BOOK_ID_1 = 1L; // public static final Long BOOK_ID_2 = 2L; // public static final Long BOOK_ID_3 = 3L; // private static final Long BOOK_ID_4 = 4L; // private static final Long USER_ID_1 = 1L; // private static final Long USER_ID_2 = 2L; // public static final String USER = "user1"; // public static final String PASSWORD_USER = "password1"; // public static final String ADMIN = "admin"; // public static final String PASSWORD_ADMIN = "password1234"; // // @Autowired // private BookRepository bookRepository; // // @Autowired // private UserAccountRepository userAccountRepository; // // @Autowired // private SequenceIdRepository sequenceRepository; // // @Autowired // private PasswordEncoder passwordEncoder; // // public void fillDBData() { // log.info("Filling DB data..."); // fillDBUsersData(); // fillDBBooksData(); // log.info("DB filled with data."); // } // // private void fillDBUsersData() { // sequenceRepository.save(new SequenceId() // .setId(USERACCOUNTS_COLLECTION) // .setSeq(USERACCOUNTS_INITIAL_SEQUENCE) // ); // userAccountRepository.deleteAll(); // Arrays.asList( // new UserAccount() // .setId(USER_ID_1) // .setUsername(USER) // .setPassword(passwordEncoder.encode(PASSWORD_USER)) // .setUserType(UserAccountType.REST_USER), // new UserAccount() // .setId(USER_ID_2) // .setUsername(ADMIN) // .setPassword(passwordEncoder.encode(PASSWORD_ADMIN)) // .setUserType(UserAccountType.ADMIN_USER)) // .forEach(userAccountRepository::save); // } // // private void fillDBBooksData() { // sequenceRepository.save(new SequenceId() // .setId(BookServiceImpl.BOOK_COLLECTION) // .setSeq(BOOKS_INITIAL_SEQUENCE) // ); // bookRepository.deleteAll(); // Arrays.asList( // new Book() // .setId(BOOK_ID_1) // .setTitle("Libro prueba mongo") // .setAuthors(Collections.singletonList(new Author().setName("Edu").setSurname("Antón"))) // .setIsbn("11-333-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 1").setCountry("ES").setOnline(false)), // new Book() // .setId(BOOK_ID_2) // .setTitle("Libro prueba mongo 2") // .setAuthors( // Arrays.asList( // new Author().setName("Otro").setSurname("Más"), // new Author().setName("S.").setSurname("King"))) // .setIsbn("12-1234-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 4").setCountry("UK").setOnline(true)), // new Book() // .setId(BOOK_ID_3) // .setTitle("Libro prueba mongo 3") // .setAuthors(Collections.singletonList(new Author().setName("Nadie").setSurname("Nobody"))) // .setIsbn("12-9999-92") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 7").setCountry("ES").setOnline(true)), // new Book() // .setId(BOOK_ID_4) // .setTitle("Libro prueba mongo 4") // .setAuthors(Collections.singletonList(new Author().setName("Perry").setSurname("Mason"))) // .setIsbn("22-34565-12") // .setReleaseDate(LocalDate.now()) // .setPublisher(new Publisher().setName("Editorial 33").setCountry("US").setOnline(true))) // .forEach(bookRepository::save); // } // } // Path: src/test/java/com/edwise/completespring/ApplicationTest.java import com.edwise.completespring.dbutils.DataLoader; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; package com.edwise.completespring; @RunWith(MockitoJUnitRunner.class) public class ApplicationTest { @Mock
private DataLoader dataLoader;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/assemblers/BookResource.java
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // }
import com.edwise.completespring.entities.Book; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.hateoas.ResourceSupport;
package com.edwise.completespring.assemblers; @Getter @Setter @Accessors(chain = true) public class BookResource extends ResourceSupport {
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java import com.edwise.completespring.entities.Book; import lombok.Getter; import lombok.Setter; import lombok.experimental.Accessors; import org.springframework.hateoas.ResourceSupport; package com.edwise.completespring.assemblers; @Getter @Setter @Accessors(chain = true) public class BookResource extends ResourceSupport {
private Book book;
edwise/complete-spring-project
src/test/java/com/edwise/completespring/assemblers/FooResourceAssemblerTest.java
// Path: src/main/java/com/edwise/completespring/entities/Foo.java // @ApiModel(value = "Foo entity", description = "Complete info of a entity foo") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Foo { // // @ApiModelProperty(value = "Sample Id Attribute", required = true) // private Long id; // // @ApiModelProperty(value = "Sample Text Attribute", required = true) // @NotNull // private String sampleTextAttribute; // // @ApiModelProperty(value = "Sample Local Date Attribute", required = true, dataType = "LocalDate") // @NotNull // private LocalDate sampleLocalDateAttribute; // // public Foo copyFrom(Foo other) { // this.sampleTextAttribute = other.sampleTextAttribute; // this.sampleLocalDateAttribute = other.sampleLocalDateAttribute; // // return this; // } // }
import com.edwise.completespring.entities.Foo; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when;
package com.edwise.completespring.assemblers; @RunWith(MockitoJUnitRunner.class) public class FooResourceAssemblerTest { private static final long FOO_ID_TEST = 1234L; @Mock
// Path: src/main/java/com/edwise/completespring/entities/Foo.java // @ApiModel(value = "Foo entity", description = "Complete info of a entity foo") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Foo { // // @ApiModelProperty(value = "Sample Id Attribute", required = true) // private Long id; // // @ApiModelProperty(value = "Sample Text Attribute", required = true) // @NotNull // private String sampleTextAttribute; // // @ApiModelProperty(value = "Sample Local Date Attribute", required = true, dataType = "LocalDate") // @NotNull // private LocalDate sampleLocalDateAttribute; // // public Foo copyFrom(Foo other) { // this.sampleTextAttribute = other.sampleTextAttribute; // this.sampleLocalDateAttribute = other.sampleLocalDateAttribute; // // return this; // } // } // Path: src/test/java/com/edwise/completespring/assemblers/FooResourceAssemblerTest.java import com.edwise.completespring.entities.Foo; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; package com.edwise.completespring.assemblers; @RunWith(MockitoJUnitRunner.class) public class FooResourceAssemblerTest { private static final long FOO_ID_TEST = 1234L; @Mock
private Foo foo;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java
// Path: src/main/java/com/edwise/completespring/exceptions/helpers/ErrorInfo.java // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class ErrorInfo implements Serializable { // // private static final long serialVersionUID = 673514291953827696L; // // @Getter // @Setter // private String url; // // @Getter // private List<ErrorItem> errors = new ArrayList<>(); // // public ErrorInfo addError(String field, String message) { // errors.add(new ErrorItem().setField(field).setMessage(message)); // return this; // } // // public static ErrorInfo generateErrorInfoFromBindingResult(BindingResult errors) { // ErrorInfo errorInfo = new ErrorInfo(); // errors.getFieldErrors() // .forEach(fieldError -> errorInfo.addError(fieldError.getField(), fieldError.getDefaultMessage())); // // return errorInfo; // } // }
import com.edwise.completespring.exceptions.helpers.ErrorInfo; import lombok.Getter; import org.springframework.validation.BindingResult;
package com.edwise.completespring.exceptions; public class InvalidRequestException extends RuntimeException { @Getter
// Path: src/main/java/com/edwise/completespring/exceptions/helpers/ErrorInfo.java // @Accessors(chain = true) // @EqualsAndHashCode(doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class ErrorInfo implements Serializable { // // private static final long serialVersionUID = 673514291953827696L; // // @Getter // @Setter // private String url; // // @Getter // private List<ErrorItem> errors = new ArrayList<>(); // // public ErrorInfo addError(String field, String message) { // errors.add(new ErrorItem().setField(field).setMessage(message)); // return this; // } // // public static ErrorInfo generateErrorInfoFromBindingResult(BindingResult errors) { // ErrorInfo errorInfo = new ErrorInfo(); // errors.getFieldErrors() // .forEach(fieldError -> errorInfo.addError(fieldError.getField(), fieldError.getDefaultMessage())); // // return errorInfo; // } // } // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java import com.edwise.completespring.exceptions.helpers.ErrorInfo; import lombok.Getter; import org.springframework.validation.BindingResult; package com.edwise.completespring.exceptions; public class InvalidRequestException extends RuntimeException { @Getter
private final ErrorInfo errors;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // }
import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository;
package com.edwise.completespring.repositories.impl; @Repository @Slf4j
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // } // Path: src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; package com.edwise.completespring.repositories.impl; @Repository @Slf4j
public class SequenceIdRepositoryImpl implements SequenceIdRepository {
edwise/complete-spring-project
src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // }
import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository;
package com.edwise.completespring.repositories.impl; @Repository @Slf4j public class SequenceIdRepositoryImpl implements SequenceIdRepository { @Autowired private MongoOperations mongoOperation; @Override public long getNextSequenceId(String key) { //get sequence id Query query = new Query(Criteria.where("_id").is(key)); //increase sequence id by 1 Update update = new Update(); update.inc("seq", 1); //return new increased id FindAndModifyOptions options = new FindAndModifyOptions(); options.returnNew(true);
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // } // Path: src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; package com.edwise.completespring.repositories.impl; @Repository @Slf4j public class SequenceIdRepositoryImpl implements SequenceIdRepository { @Autowired private MongoOperations mongoOperation; @Override public long getNextSequenceId(String key) { //get sequence id Query query = new Query(Criteria.where("_id").is(key)); //increase sequence id by 1 Update update = new Update(); update.inc("seq", 1); //return new increased id FindAndModifyOptions options = new FindAndModifyOptions(); options.returnNew(true);
SequenceId seqId =
edwise/complete-spring-project
src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // }
import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository;
package com.edwise.completespring.repositories.impl; @Repository @Slf4j public class SequenceIdRepositoryImpl implements SequenceIdRepository { @Autowired private MongoOperations mongoOperation; @Override public long getNextSequenceId(String key) { //get sequence id Query query = new Query(Criteria.where("_id").is(key)); //increase sequence id by 1 Update update = new Update(); update.inc("seq", 1); //return new increased id FindAndModifyOptions options = new FindAndModifyOptions(); options.returnNew(true); SequenceId seqId = mongoOperation.findAndModify(query, update, options, SequenceId.class); //if no id, throws SequenceException if (seqId == null) { log.error("Unable to get sequence id for key: {}", key);
// Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/exceptions/SequenceException.java // public class SequenceException extends RuntimeException { // // public SequenceException(String msg) { // super(msg); // } // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // } // Path: src/main/java/com/edwise/completespring/repositories/impl/SequenceIdRepositoryImpl.java import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.exceptions.SequenceException; import com.edwise.completespring.repositories.SequenceIdRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Repository; package com.edwise.completespring.repositories.impl; @Repository @Slf4j public class SequenceIdRepositoryImpl implements SequenceIdRepository { @Autowired private MongoOperations mongoOperation; @Override public long getNextSequenceId(String key) { //get sequence id Query query = new Query(Criteria.where("_id").is(key)); //increase sequence id by 1 Update update = new Update(); update.inc("seq", 1); //return new increased id FindAndModifyOptions options = new FindAndModifyOptions(); options.returnNew(true); SequenceId seqId = mongoOperation.findAndModify(query, update, options, SequenceId.class); //if no id, throws SequenceException if (seqId == null) { log.error("Unable to get sequence id for key: {}", key);
throw new SequenceException("Unable to get sequence id for key: " + key);
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // }
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // } // Path: src/main/java/com/edwise/completespring/controllers/BookController.java import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List; package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired
private BookResourceAssembler bookResourceAssembler;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // }
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // } // Path: src/main/java/com/edwise/completespring/controllers/BookController.java import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List; package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired
private BookService bookService;
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // }
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired private BookService bookService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Books", notes = "Returns all books") @ApiResponses({
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // } // Path: src/main/java/com/edwise/completespring/controllers/BookController.java import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List; package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired private BookService bookService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Books", notes = "Returns all books") @ApiResponses({
@ApiResponse(code = RESPONSE_CODE_OK, response = BookResource.class, message = "Exits one book at least")
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // }
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired private BookService bookService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Books", notes = "Returns all books") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, response = BookResource.class, message = "Exits one book at least") }) public ResponseEntity<List<BookResource>> getAll() {
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // } // Path: src/main/java/com/edwise/completespring/controllers/BookController.java import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List; package com.edwise.completespring.controllers; @RestController @RequestMapping("/api/books/") @Api(value = "books", description = "Books API", produces = "application/json") @Slf4j public class BookController { private static final int RESPONSE_CODE_OK = 200; private static final int RESPONSE_CODE_CREATED = 201; private static final int RESPONSE_CODE_NO_RESPONSE = 204; @Autowired private BookResourceAssembler bookResourceAssembler; @Autowired private BookService bookService; @RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get Books", notes = "Returns all books") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, response = BookResource.class, message = "Exits one book at least") }) public ResponseEntity<List<BookResource>> getAll() {
List<Book> books = bookService.findAll();
edwise/complete-spring-project
src/main/java/com/edwise/completespring/controllers/BookController.java
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // }
import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List;
}) public ResponseEntity<List<BookResource>> getAll() { List<Book> books = bookService.findAll(); List<BookResource> resourceList = bookResourceAssembler.toResources(books); log.info("Books found: {}", books); return new ResponseEntity<>(resourceList, HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET, value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get one Book", response = BookResource.class, notes = "Returns one book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, message = "Exists this book") }) public ResponseEntity<BookResource> getBook(@ApiParam(defaultValue = "1", value = "The id of the book to return") @PathVariable long id) { Book book = bookService.findOne(id); log.info("Book found: {}", book); return new ResponseEntity<>(bookResourceAssembler.toResource(book), HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create Book", notes = "Create a book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_CREATED, message = "Successful create of a book") }) public ResponseEntity<BookResource> createBook(@Valid @RequestBody Book book, BindingResult errors) { if (errors.hasErrors()) {
// Path: src/main/java/com/edwise/completespring/assemblers/BookResource.java // @Getter // @Setter // @Accessors(chain = true) // public class BookResource extends ResourceSupport { // private Book book; // } // // Path: src/main/java/com/edwise/completespring/assemblers/BookResourceAssembler.java // @Component // public class BookResourceAssembler extends ResourceAssemblerSupport<Book, BookResource> { // // public BookResourceAssembler() { // super(BookController.class, BookResource.class); // } // // @Override // protected BookResource instantiateResource(Book book) { // BookResource bookResource = super.instantiateResource(book); // bookResource.setBook(book); // // return bookResource; // } // // public BookResource toResource(Book book) { // return createResourceWithId(book.getId(), book); // } // } // // Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/exceptions/InvalidRequestException.java // public class InvalidRequestException extends RuntimeException { // // @Getter // private final ErrorInfo errors; // // public InvalidRequestException(BindingResult bindingResultErrors) { // super(bindingResultErrors.toString()); // this.errors = ErrorInfo.generateErrorInfoFromBindingResult(bindingResultErrors); // } // // } // // Path: src/main/java/com/edwise/completespring/services/BookService.java // public interface BookService extends Service<Book, Long> { // // List<Book> findByTitle(String title); // // List<Book> findByReleaseDate(LocalDate releaseDate); // // Book create(Book book); // } // Path: src/main/java/com/edwise/completespring/controllers/BookController.java import com.edwise.completespring.assemblers.BookResource; import com.edwise.completespring.assemblers.BookResourceAssembler; import com.edwise.completespring.entities.Book; import com.edwise.completespring.exceptions.InvalidRequestException; import com.edwise.completespring.services.BookService; import io.swagger.annotations.*; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.hateoas.Link; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.net.URI; import java.util.List; }) public ResponseEntity<List<BookResource>> getAll() { List<Book> books = bookService.findAll(); List<BookResource> resourceList = bookResourceAssembler.toResources(books); log.info("Books found: {}", books); return new ResponseEntity<>(resourceList, HttpStatus.OK); } @RequestMapping(method = RequestMethod.GET, value = "{id}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get one Book", response = BookResource.class, notes = "Returns one book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_OK, message = "Exists this book") }) public ResponseEntity<BookResource> getBook(@ApiParam(defaultValue = "1", value = "The id of the book to return") @PathVariable long id) { Book book = bookService.findOne(id); log.info("Book found: {}", book); return new ResponseEntity<>(bookResourceAssembler.toResource(book), HttpStatus.OK); } @RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Create Book", notes = "Create a book") @ApiResponses({ @ApiResponse(code = RESPONSE_CODE_CREATED, message = "Successful create of a book") }) public ResponseEntity<BookResource> createBook(@Valid @RequestBody Book book, BindingResult errors) { if (errors.hasErrors()) {
throw new InvalidRequestException(errors);
edwise/complete-spring-project
src/test/java/com/edwise/completespring/dbutils/DataLoaderTest.java
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/entities/UserAccount.java // @Document(collection = "users") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class UserAccount { // // @Id // private Long id; // // private String username; // private String password; // // @NonNull // private UserAccountType userType = UserAccountType.REST_USER; // } // // Path: src/main/java/com/edwise/completespring/repositories/BookRepository.java // public interface BookRepository extends MongoRepository<Book, Long> { // // List<Book> findByTitle(String title); // List<Book> findByReleaseDate(LocalDate releaseDate); // // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // } // // Path: src/main/java/com/edwise/completespring/repositories/UserAccountRepository.java // public interface UserAccountRepository extends MongoRepository<UserAccount, Long> { // // UserAccount findByUsername(String username); // }
import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.entities.UserAccount; import com.edwise.completespring.repositories.BookRepository; import com.edwise.completespring.repositories.SequenceIdRepository; import com.edwise.completespring.repositories.UserAccountRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
package com.edwise.completespring.dbutils; @RunWith(MockitoJUnitRunner.class) public class DataLoaderTest { private static final int TWO_TIMES = 2; private static final int FOUR_TIMES = 4; @Mock
// Path: src/main/java/com/edwise/completespring/entities/Book.java // @Document(collection = "books") // @ApiModel(value = "Book entity", description = "Complete info of a entity book") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class Book { // // @ApiModelProperty(value = "The id of the book") // @Id // private Long id; // // @ApiModelProperty(value = "The title of the book", required = true) // @NotEmpty // private String title; // // @ApiModelProperty(value = "The authors of the book", required = true) // @Valid // private List<Author> authors; // // @ApiModelProperty(value = "The isbn of the book", required = true) // @NotEmpty // private String isbn; // // @ApiModelProperty(value = "The release date of the book", required = true, dataType = "LocalDate") // @NotNull // private LocalDate releaseDate; // // @ApiModelProperty(value = "The publisher of the book", required = true) // @Valid // @NotNull // private Publisher publisher; // // public Book copyFrom(Book other) { // this.title = other.title; // if (other.authors != null) { // this.authors = new ArrayList<>(); // this.authors.addAll(other.authors.stream().map(new Author()::copyFrom).collect(Collectors.toList())); // } // this.isbn = other.isbn; // this.releaseDate = other.releaseDate; // if (other.publisher != null) { // this.publisher = new Publisher().copyFrom(other.publisher); // } // // return this; // } // } // // Path: src/main/java/com/edwise/completespring/entities/SequenceId.java // @Document(collection = "sequences") // @Setter @Getter // @Accessors(chain = true) // @ToString(doNotUseGetters = true) // public class SequenceId { // @Id // private String id; // // private long seq; // // } // // Path: src/main/java/com/edwise/completespring/entities/UserAccount.java // @Document(collection = "users") // @Data // @Accessors(chain = true) // @EqualsAndHashCode(exclude = {"id"}, doNotUseGetters = true) // @ToString(doNotUseGetters = true) // public class UserAccount { // // @Id // private Long id; // // private String username; // private String password; // // @NonNull // private UserAccountType userType = UserAccountType.REST_USER; // } // // Path: src/main/java/com/edwise/completespring/repositories/BookRepository.java // public interface BookRepository extends MongoRepository<Book, Long> { // // List<Book> findByTitle(String title); // List<Book> findByReleaseDate(LocalDate releaseDate); // // } // // Path: src/main/java/com/edwise/completespring/repositories/SequenceIdRepository.java // public interface SequenceIdRepository { // void save(SequenceId sequenceId); // // long getNextSequenceId(String key); // } // // Path: src/main/java/com/edwise/completespring/repositories/UserAccountRepository.java // public interface UserAccountRepository extends MongoRepository<UserAccount, Long> { // // UserAccount findByUsername(String username); // } // Path: src/test/java/com/edwise/completespring/dbutils/DataLoaderTest.java import com.edwise.completespring.entities.Book; import com.edwise.completespring.entities.SequenceId; import com.edwise.completespring.entities.UserAccount; import com.edwise.completespring.repositories.BookRepository; import com.edwise.completespring.repositories.SequenceIdRepository; import com.edwise.completespring.repositories.UserAccountRepository; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; package com.edwise.completespring.dbutils; @RunWith(MockitoJUnitRunner.class) public class DataLoaderTest { private static final int TWO_TIMES = 2; private static final int FOUR_TIMES = 4; @Mock
private BookRepository bookRepository;