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
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/FindPersonTask.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/UseCase.java // public abstract class UseCase<Request, Response> { // private UseCaseCallback<Response> callback; // private Request request; // // // @WorkerThread // protected abstract void onExecute(); // // /** // * Passes the use case by logging it and invoking the appropriate callback // * with the response data from the successful execution. // * @param response Response data // */ // protected final void pass(final Response response) { // Log.i(getClass().getSimpleName().toUpperCase(), "Success!"); // this.callback.onSuccess(response); // } // // /** // * Fails the use case by logging it and invoking the appropriate callback // * containing information about by it fail execution. // * @param ex {@link Exception} // */ // protected final void fail(final Exception ex) { // Log.wtf(getClass().getSimpleName().toUpperCase(), "Failed!", ex); // this.callback.onFailure(ex); // } // // public Request getRequest() { // return request; // } // // void setRequest(final Request request) { // this.request = request; // } // // void setCallback(final UseCaseCallback<Response> callback) { // this.callback = callback; // } // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.UseCase;
package com.tylersuehr.cleanarchitecture.domain.people; /** * Copyright 2017 Tyler Suehr * * Business logic to find a person in the repository. * Request: Person's id. * Response: Valid {@link Person}. * * @author Tyler Suehr * @version 1.0 */ public class FindPersonTask extends UseCase<String, Person> { private final IPersonRepository personRepo; public FindPersonTask(IPersonRepository personRepo) { this.personRepo = personRepo; } @Override protected void onExecute() { final String personId = getRequest();
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/UseCase.java // public abstract class UseCase<Request, Response> { // private UseCaseCallback<Response> callback; // private Request request; // // // @WorkerThread // protected abstract void onExecute(); // // /** // * Passes the use case by logging it and invoking the appropriate callback // * with the response data from the successful execution. // * @param response Response data // */ // protected final void pass(final Response response) { // Log.i(getClass().getSimpleName().toUpperCase(), "Success!"); // this.callback.onSuccess(response); // } // // /** // * Fails the use case by logging it and invoking the appropriate callback // * containing information about by it fail execution. // * @param ex {@link Exception} // */ // protected final void fail(final Exception ex) { // Log.wtf(getClass().getSimpleName().toUpperCase(), "Failed!", ex); // this.callback.onFailure(ex); // } // // public Request getRequest() { // return request; // } // // void setRequest(final Request request) { // this.request = request; // } // // void setCallback(final UseCaseCallback<Response> callback) { // this.callback = callback; // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/FindPersonTask.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.UseCase; package com.tylersuehr.cleanarchitecture.domain.people; /** * Copyright 2017 Tyler Suehr * * Business logic to find a person in the repository. * Request: Person's id. * Response: Valid {@link Person}. * * @author Tyler Suehr * @version 1.0 */ public class FindPersonTask extends UseCase<String, Person> { private final IPersonRepository personRepo; public FindPersonTask(IPersonRepository personRepo) { this.personRepo = personRepo; } @Override protected void onExecute() { final String personId = getRequest();
this.personRepo.findPersonById(personId, new Callbacks.ISingle<Person>() {
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/UseCase.java // public abstract class UseCase<Request, Response> { // private UseCaseCallback<Response> callback; // private Request request; // // // @WorkerThread // protected abstract void onExecute(); // // /** // * Passes the use case by logging it and invoking the appropriate callback // * with the response data from the successful execution. // * @param response Response data // */ // protected final void pass(final Response response) { // Log.i(getClass().getSimpleName().toUpperCase(), "Success!"); // this.callback.onSuccess(response); // } // // /** // * Fails the use case by logging it and invoking the appropriate callback // * containing information about by it fail execution. // * @param ex {@link Exception} // */ // protected final void fail(final Exception ex) { // Log.wtf(getClass().getSimpleName().toUpperCase(), "Failed!", ex); // this.callback.onFailure(ex); // } // // public Request getRequest() { // return request; // } // // void setRequest(final Request request) { // this.request = request; // } // // void setCallback(final UseCaseCallback<Response> callback) { // this.callback = callback; // } // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.UseCase; import java.util.List;
package com.tylersuehr.cleanarchitecture.domain.people; /** * Copyright 2017 Tyler Suehr * * Business logic to load all people from the repository. * Request: nothing. * Response: List of {@link Person} * * @author Tyler Suehr * @version 1.0 */ public class AllPeopleTask extends UseCase<Object, List<Person>> { private IPersonRepository personRepo; public AllPeopleTask(IPersonRepository personRepo) { this.personRepo = personRepo; } @Override protected void onExecute() {
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/UseCase.java // public abstract class UseCase<Request, Response> { // private UseCaseCallback<Response> callback; // private Request request; // // // @WorkerThread // protected abstract void onExecute(); // // /** // * Passes the use case by logging it and invoking the appropriate callback // * with the response data from the successful execution. // * @param response Response data // */ // protected final void pass(final Response response) { // Log.i(getClass().getSimpleName().toUpperCase(), "Success!"); // this.callback.onSuccess(response); // } // // /** // * Fails the use case by logging it and invoking the appropriate callback // * containing information about by it fail execution. // * @param ex {@link Exception} // */ // protected final void fail(final Exception ex) { // Log.wtf(getClass().getSimpleName().toUpperCase(), "Failed!", ex); // this.callback.onFailure(ex); // } // // public Request getRequest() { // return request; // } // // void setRequest(final Request request) { // this.request = request; // } // // void setCallback(final UseCaseCallback<Response> callback) { // this.callback = callback; // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.UseCase; import java.util.List; package com.tylersuehr.cleanarchitecture.domain.people; /** * Copyright 2017 Tyler Suehr * * Business logic to load all people from the repository. * Request: nothing. * Response: List of {@link Person} * * @author Tyler Suehr * @version 1.0 */ public class AllPeopleTask extends UseCase<Object, List<Person>> { private IPersonRepository personRepo; public AllPeopleTask(IPersonRepository personRepo) { this.personRepo = personRepo; } @Override protected void onExecute() {
this.personRepo.findAllPeople(new Callbacks.IList<Person>() {
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // }
import android.support.annotation.Nullable; import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks;
package com.tylersuehr.cleanarchitecture.data.repositories.people; /** * Copyright 2017 Tyler Suehr * * Defines the core methods needed to manipulate the person repository. * * @author Tyler Suehr * @version 1.0 */ public interface IPersonRepository { /** * Creates a new person in the repository. * @param person {@link Person} * @throws Exception if create fails */ void createPerson(Person person) throws Exception; /** * Deletes a person in the repository. Leave null to delete all * people in the repository. * @param person {@link Person} * * @throws Exception if deletion fails */ void deletePerson(@Nullable Person person) throws Exception; /** * Finds all people in the repository. * @param callback {@link Callbacks.IList} */
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java import android.support.annotation.Nullable; import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; package com.tylersuehr.cleanarchitecture.data.repositories.people; /** * Copyright 2017 Tyler Suehr * * Defines the core methods needed to manipulate the person repository. * * @author Tyler Suehr * @version 1.0 */ public interface IPersonRepository { /** * Creates a new person in the repository. * @param person {@link Person} * @throws Exception if create fails */ void createPerson(Person person) throws Exception; /** * Deletes a person in the repository. Leave null to delete all * people in the repository. * @param person {@link Person} * * @throws Exception if deletion fails */ void deletePerson(@Nullable Person person) throws Exception; /** * Finds all people in the repository. * @param callback {@link Callbacks.IList} */
void findAllPeople(Callbacks.IList<Person> callback);
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Entity.java // public abstract class Entity { // private Object id; // // // @Override // public boolean equals(Object obj) { // return (this == obj) || (obj instanceof Entity && ((Entity)obj).id.equals(id)); // } // // @Override // public String toString() { // return "Entity {'" + id + "'}"; // } // // public Object getId() { // return id; // } // // public void setId(Object id) { // this.id = id; // } // }
import com.tylersuehr.cleanarchitecture.data.models.Entity; import java.util.List;
package com.tylersuehr.cleanarchitecture.data.repositories; /** * Copyright © 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public interface Callbacks { /** * Defines an interface for handling an error callback. */ interface IError { void onNotAvailable(Exception ex); } /** * Defines an interface for handling a single response callback. */
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Entity.java // public abstract class Entity { // private Object id; // // // @Override // public boolean equals(Object obj) { // return (this == obj) || (obj instanceof Entity && ((Entity)obj).id.equals(id)); // } // // @Override // public String toString() { // return "Entity {'" + id + "'}"; // } // // public Object getId() { // return id; // } // // public void setId(Object id) { // this.id = id; // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java import com.tylersuehr.cleanarchitecture.data.models.Entity; import java.util.List; package com.tylersuehr.cleanarchitecture.data.repositories; /** * Copyright © 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public interface Callbacks { /** * Defines an interface for handling an error callback. */ interface IError { void onNotAvailable(Exception ex); } /** * Defines an interface for handling a single response callback. */
interface ISingle<T extends Entity> extends IError {
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment
IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext());
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment
IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext());
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter(
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter(
new AllPeopleTask(personRepo),
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter( new AllPeopleTask(personRepo),
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter( new AllPeopleTask(personRepo),
new CreatePersonTask(personRepo),
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter( new AllPeopleTask(personRepo), new CreatePersonTask(personRepo),
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/Injector.java // public final class Injector { // public static PersonRepository providePeopleRepo(Context appCtx) { // return PersonRepository.getInstance(new LocalPersonRepository( // DatabaseClient.getInstance(appCtx), new PersonMapper() // )); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/IPersonRepository.java // public interface IPersonRepository { // /** // * Creates a new person in the repository. // * @param person {@link Person} // * @throws Exception if create fails // */ // void createPerson(Person person) throws Exception; // // /** // * Deletes a person in the repository. Leave null to delete all // * people in the repository. // * @param person {@link Person} // * // * @throws Exception if deletion fails // */ // void deletePerson(@Nullable Person person) throws Exception; // // /** // * Finds all people in the repository. // * @param callback {@link Callbacks.IList} // */ // void findAllPeople(Callbacks.IList<Person> callback); // // /** // * Finds a person in the repository using their profile ID. // * @param personId Person's profile ID // * @param callback {@link Callbacks.ISingle} // */ // void findPersonById(String personId, Callbacks.ISingle<Person> callback); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/AllPeopleTask.java // public class AllPeopleTask extends UseCase<Object, List<Person>> { // private IPersonRepository personRepo; // // // public AllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // this.personRepo.findAllPeople(new Callbacks.IList<Person>() { // @Override // public void onListLoaded(List<Person> people) { // pass(people); // } // // @Override // public void onNotAvailable(Exception ex) { // fail(ex); // } // }); // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/DeleteAllPeopleTask.java // public class DeleteAllPeopleTask extends UseCase<Object, Object> { // private final IPersonRepository personRepo; // // // public DeleteAllPeopleTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // this.personRepo.deletePerson(null); // pass(null); // } catch (Exception ex) { // fail(ex); // } // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/domain/people/CreatePersonTask.java // public class CreatePersonTask extends UseCase<CreatePersonTask.Request, Person> { // private final IPersonRepository personRepo; // // // public CreatePersonTask(IPersonRepository personRepo) { // this.personRepo = personRepo; // } // // @Override // protected void onExecute() { // try { // final Request request = getRequest(); // // // Create the person model // Person person = new Person(); // person.setId(UUID.randomUUID().toString()); // person.setFirstName(request.first); // person.setLastName(request.last); // person.setImage(request.image); // person.setAge(request.age); // // // Save person in the repository // this.personRepo.createPerson(person); // // // Callback with the valid model // pass(person); // } catch (Exception ex) { // fail(ex); // } // } // // public static final class Request { // private final String first; // private final String last; // private final String image; // private final int age; // // public Request(String first, String last, String image, int age) { // this.first = first; // this.last = last; // this.image = image; // this.age = age; // } // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import com.tylersuehr.cleanarchitecture.R; import com.tylersuehr.cleanarchitecture.data.Injector; import com.tylersuehr.cleanarchitecture.data.repositories.people.IPersonRepository; import com.tylersuehr.cleanarchitecture.domain.people.AllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.DeleteAllPeopleTask; import com.tylersuehr.cleanarchitecture.domain.people.CreatePersonTask; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright 2017 Tyler Suehr * * @author Tyler Suehr * @version 1.0 */ public class PeopleActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_people); // Setup toolbar Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Show the people fragment IPersonRepository personRepo = Injector.providePeopleRepo(getApplicationContext()); getSupportFragmentManager() .beginTransaction() .replace(R.id.body, PeopleFragment.create( new PeoplePresenter( new AllPeopleTask(personRepo), new CreatePersonTask(personRepo),
new DeleteAllPeopleTask(personRepo)
citerus/dddsample-core
src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*;
package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*; package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
GraphTraversalService graphTraversalService = new GraphTraversalServiceImpl(new GraphDAOStub() {
citerus/dddsample-core
src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*;
package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*; package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
GraphTraversalService graphTraversalService = new GraphTraversalServiceImpl(new GraphDAOStub() {
citerus/dddsample-core
src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*;
package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/test/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingServiceTest.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.junit.Before; import org.junit.Test; import se.citerus.dddsample.domain.model.cargo.*; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.voyage.SampleVoyages; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.infrastructure.persistence.inmemory.LocationRepositoryInMem; import java.util.Arrays; import java.util.Date; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static se.citerus.dddsample.domain.model.location.SampleLocations.*; package se.citerus.dddsample.infrastructure.routing; public class ExternalRoutingServiceTest { private ExternalRoutingService externalRoutingService; private VoyageRepository voyageRepository; @Before public void setUp() { externalRoutingService = new ExternalRoutingService(); LocationRepository locationRepository = new LocationRepositoryInMem(); externalRoutingService.setLocationRepository(locationRepository); voyageRepository = mock(VoyageRepository.class); externalRoutingService.setVoyageRepository(voyageRepository);
GraphTraversalService graphTraversalService = new GraphTraversalServiceImpl(new GraphDAOStub() {
citerus/dddsample-core
src/main/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingService.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/api/TransitEdge.java // public final class TransitEdge implements Serializable { // // private final String edge; // private final String fromNode; // private final String toNode; // private final Date fromDate; // private final Date toDate; // // /** // * Constructor. // * // * @param edge // * @param fromNode // * @param toNode // * @param fromDate // * @param toDate // */ // public TransitEdge(final String edge, // final String fromNode, // final String toNode, // final Date fromDate, // final Date toDate) { // this.edge = edge; // this.fromNode = fromNode; // this.toNode = toNode; // this.fromDate = fromDate; // this.toDate = toDate; // } // // public String getEdge() { // return edge; // } // // public String getFromNode() { // return fromNode; // } // // public String getToNode() { // return toNode; // } // // public Date getFromDate() { // return fromDate; // } // // public Date getToDate() { // return toDate; // } // } // // Path: src/main/java/se/citerus/dddsample/domain/model/cargo/RouteSpecification.java // public class RouteSpecification extends AbstractSpecification<Itinerary> implements ValueObject<RouteSpecification> { // // private Location origin; // private Location destination; // private Date arrivalDeadline; // // /** // * @param origin origin location - can't be the same as the destination // * @param destination destination location - can't be the same as the origin // * @param arrivalDeadline arrival deadline // */ // public RouteSpecification(final Location origin, final Location destination, final Date arrivalDeadline) { // Validate.notNull(origin, "Origin is required"); // Validate.notNull(destination, "Destination is required"); // Validate.notNull(arrivalDeadline, "Arrival deadline is required"); // Validate.isTrue(!origin.sameIdentityAs(destination), "Origin and destination can't be the same: " + origin); // // this.origin = origin; // this.destination = destination; // this.arrivalDeadline = (Date) arrivalDeadline.clone(); // } // // /** // * @return Specified origin location. // */ // public Location origin() { // return origin; // } // // /** // * @return Specfied destination location. // */ // public Location destination() { // return destination; // } // // /** // * @return Arrival deadline. // */ // public Date arrivalDeadline() { // return new Date(arrivalDeadline.getTime()); // } // // @Override // public boolean isSatisfiedBy(final Itinerary itinerary) { // return itinerary != null && // origin().sameIdentityAs(itinerary.initialDepartureLocation()) && // destination().sameIdentityAs(itinerary.finalArrivalLocation()) && // arrivalDeadline().after(itinerary.finalArrivalDate()); // } // // @Override // public boolean sameValueAs(final RouteSpecification other) { // return other != null && new EqualsBuilder(). // append(this.origin, other.origin). // append(this.destination, other.destination). // append(this.arrivalDeadline, other.arrivalDeadline). // isEquals(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final RouteSpecification that = (RouteSpecification) o; // // return sameValueAs(that); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(). // append(this.origin). // append(this.destination). // append(this.arrivalDeadline). // toHashCode(); // } // // RouteSpecification() { // // Needed by Hibernate // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.api.TransitEdge; import com.pathfinder.api.TransitPath; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import se.citerus.dddsample.domain.model.cargo.Itinerary; import se.citerus.dddsample.domain.model.cargo.Leg; import se.citerus.dddsample.domain.model.cargo.RouteSpecification; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.location.UnLocode; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.domain.service.RoutingService; import java.util.ArrayList; import java.util.List; import java.util.Properties;
package se.citerus.dddsample.infrastructure.routing; /** * Our end of the routing service. This is basically a data model * translation layer between our domain model and the API put forward * by the routing team, which operates in a different context from us. * */ public class ExternalRoutingService implements RoutingService { private GraphTraversalService graphTraversalService; private LocationRepository locationRepository; private VoyageRepository voyageRepository; private static final Log log = LogFactory.getLog(ExternalRoutingService.class);
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/api/TransitEdge.java // public final class TransitEdge implements Serializable { // // private final String edge; // private final String fromNode; // private final String toNode; // private final Date fromDate; // private final Date toDate; // // /** // * Constructor. // * // * @param edge // * @param fromNode // * @param toNode // * @param fromDate // * @param toDate // */ // public TransitEdge(final String edge, // final String fromNode, // final String toNode, // final Date fromDate, // final Date toDate) { // this.edge = edge; // this.fromNode = fromNode; // this.toNode = toNode; // this.fromDate = fromDate; // this.toDate = toDate; // } // // public String getEdge() { // return edge; // } // // public String getFromNode() { // return fromNode; // } // // public String getToNode() { // return toNode; // } // // public Date getFromDate() { // return fromDate; // } // // public Date getToDate() { // return toDate; // } // } // // Path: src/main/java/se/citerus/dddsample/domain/model/cargo/RouteSpecification.java // public class RouteSpecification extends AbstractSpecification<Itinerary> implements ValueObject<RouteSpecification> { // // private Location origin; // private Location destination; // private Date arrivalDeadline; // // /** // * @param origin origin location - can't be the same as the destination // * @param destination destination location - can't be the same as the origin // * @param arrivalDeadline arrival deadline // */ // public RouteSpecification(final Location origin, final Location destination, final Date arrivalDeadline) { // Validate.notNull(origin, "Origin is required"); // Validate.notNull(destination, "Destination is required"); // Validate.notNull(arrivalDeadline, "Arrival deadline is required"); // Validate.isTrue(!origin.sameIdentityAs(destination), "Origin and destination can't be the same: " + origin); // // this.origin = origin; // this.destination = destination; // this.arrivalDeadline = (Date) arrivalDeadline.clone(); // } // // /** // * @return Specified origin location. // */ // public Location origin() { // return origin; // } // // /** // * @return Specfied destination location. // */ // public Location destination() { // return destination; // } // // /** // * @return Arrival deadline. // */ // public Date arrivalDeadline() { // return new Date(arrivalDeadline.getTime()); // } // // @Override // public boolean isSatisfiedBy(final Itinerary itinerary) { // return itinerary != null && // origin().sameIdentityAs(itinerary.initialDepartureLocation()) && // destination().sameIdentityAs(itinerary.finalArrivalLocation()) && // arrivalDeadline().after(itinerary.finalArrivalDate()); // } // // @Override // public boolean sameValueAs(final RouteSpecification other) { // return other != null && new EqualsBuilder(). // append(this.origin, other.origin). // append(this.destination, other.destination). // append(this.arrivalDeadline, other.arrivalDeadline). // isEquals(); // } // // @Override // public boolean equals(final Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // final RouteSpecification that = (RouteSpecification) o; // // return sameValueAs(that); // } // // @Override // public int hashCode() { // return new HashCodeBuilder(). // append(this.origin). // append(this.destination). // append(this.arrivalDeadline). // toHashCode(); // } // // RouteSpecification() { // // Needed by Hibernate // } // // } // Path: src/main/java/se/citerus/dddsample/infrastructure/routing/ExternalRoutingService.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.api.TransitEdge; import com.pathfinder.api.TransitPath; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import se.citerus.dddsample.domain.model.cargo.Itinerary; import se.citerus.dddsample.domain.model.cargo.Leg; import se.citerus.dddsample.domain.model.cargo.RouteSpecification; import se.citerus.dddsample.domain.model.location.Location; import se.citerus.dddsample.domain.model.location.LocationRepository; import se.citerus.dddsample.domain.model.location.UnLocode; import se.citerus.dddsample.domain.model.voyage.VoyageNumber; import se.citerus.dddsample.domain.model.voyage.VoyageRepository; import se.citerus.dddsample.domain.service.RoutingService; import java.util.ArrayList; import java.util.List; import java.util.Properties; package se.citerus.dddsample.infrastructure.routing; /** * Our end of the routing service. This is basically a data model * translation layer between our domain model and the API put forward * by the routing team, which operates in a different context from us. * */ public class ExternalRoutingService implements RoutingService { private GraphTraversalService graphTraversalService; private LocationRepository locationRepository; private VoyageRepository voyageRepository; private static final Log log = LogFactory.getLog(ExternalRoutingService.class);
public List<Itinerary> fetchRoutesForSpecification(RouteSpecification routeSpecification) {
citerus/dddsample-core
src/test/java/se/citerus/dddsample/acceptance/AdminAcceptanceTest.java
// Path: src/test/java/se/citerus/dddsample/acceptance/pages/AdminPage.java // public class AdminPage { // private final WebDriver driver; // // public AdminPage(WebDriver driver) { // this.driver = driver; // driver.get("http://localhost:8080/dddsample/admin/list"); // assertEquals("Cargo Administration", driver.getTitle()); // } // // public void listAllCargo() { // driver.findElement(By.linkText("List all cargos")).click(); // assertEquals("Cargo Administration", driver.getTitle()); // } // // public CargoBookingPage bookNewCargo() { // driver.findElement(By.linkText("Book new cargo")).click(); // // return new CargoBookingPage(driver); // } // // public boolean listedCargoContains(String expectedTrackingId) { // List<WebElement> cargoList = driver.findElements(By.cssSelector("#body table tbody tr td a")); // Optional<WebElement> matchingCargo = cargoList.stream().filter(cargo -> cargo.getText().equals(expectedTrackingId)).findFirst(); // return matchingCargo.isPresent(); // } // // public CargoDetailsPage showDetailsFor(String cargoTrackingId) { // driver.findElement(By.linkText(cargoTrackingId)).click(); // // return new CargoDetailsPage(driver); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoBookingPage.java // public class CargoBookingPage { // // private final WebDriver driver; // // public CargoBookingPage(WebDriver driver) { // this.driver = driver; // // WebElement newCargoTableCaption = driver.findElement(By.cssSelector("table caption")); // // assertEquals("Book new cargo", newCargoTableCaption.getText()); // } // // public void selectOrigin(String origin) { // Select select = new Select(driver.findElement(By.name("originUnlocode"))); // select.selectByVisibleText(origin); // } // // public void selectDestination(String destination) { // Select select = new Select(driver.findElement(By.name("destinationUnlocode"))); // select.selectByVisibleText(destination); // } // // public CargoDetailsPage book() { // driver.findElement(By.name("originUnlocode")).submit(); // // return new CargoDetailsPage(driver); // } // // public void selectArrivalDeadline(LocalDate arrivalDeadline) { // WebElement datePicker = driver.findElement(By.id("arrivalDeadline")); // datePicker.clear(); // datePicker.sendKeys(arrivalDeadline.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoDestinationPage.java // public class CargoDestinationPage { // private final WebDriver driver; // // public CargoDestinationPage(WebDriver driver) { // this.driver = driver; // WebElement cargoDestinationHeader = driver.findElement(By.cssSelector("table caption")); // // assertTrue(cargoDestinationHeader.getText().startsWith("Change destination for cargo ")); // } // // public CargoDetailsPage selectDestinationTo(String destination) { // WebElement destinationPicker = driver.findElement(By.name("unlocode")); // Select select = new Select(destinationPicker); // select.selectByVisibleText(destination); // // destinationPicker.submit(); // // return new CargoDetailsPage(driver); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoDetailsPage.java // public class CargoDetailsPage { // public static final String TRACKING_ID_HEADER = "Details for cargo "; // private final WebDriver driver; // private String trackingId; // // public CargoDetailsPage(WebDriver driver) { // this.driver = driver; // // WebElement newCargoTableCaption = driver.findElement(By.cssSelector("table caption")); // // assertTrue(newCargoTableCaption.getText().startsWith(TRACKING_ID_HEADER)); // trackingId = newCargoTableCaption.getText().replaceFirst(TRACKING_ID_HEADER, ""); // } // // public String getTrackingId() { // return trackingId; // } // // public AdminPage listAllCargo() { // driver.findElement(By.linkText("List all cargos")).click(); // // return new AdminPage(driver); // } // // public void expectOriginOf(String expectedOrigin) { // String actualOrigin = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[1]/td[2]")).getText(); // // assertEquals(expectedOrigin, actualOrigin); // } // // public void expectDestinationOf(String expectedDestination) { // String actualDestination = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[2]/td[2]")).getText(); // // assertEquals(expectedDestination, actualDestination); // } // // public CargoDestinationPage changeDestination() { // driver.findElement(By.linkText("Change destination")).click(); // // return new CargoDestinationPage(driver); // } // // public void expectArrivalDeadlineOf(LocalDate expectedArrivalDeadline) { // String actualArrivalDeadline = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[4]/td[2]")).getText(); // // assertEquals(expectedArrivalDeadline.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")), actualArrivalDeadline); // } // }
import org.junit.Test; import se.citerus.dddsample.acceptance.pages.AdminPage; import se.citerus.dddsample.acceptance.pages.CargoBookingPage; import se.citerus.dddsample.acceptance.pages.CargoDestinationPage; import se.citerus.dddsample.acceptance.pages.CargoDetailsPage; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import static junit.framework.TestCase.assertTrue;
package se.citerus.dddsample.acceptance; public class AdminAcceptanceTest extends AbstractAcceptanceTest { @Test public void adminSiteCargoListContainsCannedCargo() {
// Path: src/test/java/se/citerus/dddsample/acceptance/pages/AdminPage.java // public class AdminPage { // private final WebDriver driver; // // public AdminPage(WebDriver driver) { // this.driver = driver; // driver.get("http://localhost:8080/dddsample/admin/list"); // assertEquals("Cargo Administration", driver.getTitle()); // } // // public void listAllCargo() { // driver.findElement(By.linkText("List all cargos")).click(); // assertEquals("Cargo Administration", driver.getTitle()); // } // // public CargoBookingPage bookNewCargo() { // driver.findElement(By.linkText("Book new cargo")).click(); // // return new CargoBookingPage(driver); // } // // public boolean listedCargoContains(String expectedTrackingId) { // List<WebElement> cargoList = driver.findElements(By.cssSelector("#body table tbody tr td a")); // Optional<WebElement> matchingCargo = cargoList.stream().filter(cargo -> cargo.getText().equals(expectedTrackingId)).findFirst(); // return matchingCargo.isPresent(); // } // // public CargoDetailsPage showDetailsFor(String cargoTrackingId) { // driver.findElement(By.linkText(cargoTrackingId)).click(); // // return new CargoDetailsPage(driver); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoBookingPage.java // public class CargoBookingPage { // // private final WebDriver driver; // // public CargoBookingPage(WebDriver driver) { // this.driver = driver; // // WebElement newCargoTableCaption = driver.findElement(By.cssSelector("table caption")); // // assertEquals("Book new cargo", newCargoTableCaption.getText()); // } // // public void selectOrigin(String origin) { // Select select = new Select(driver.findElement(By.name("originUnlocode"))); // select.selectByVisibleText(origin); // } // // public void selectDestination(String destination) { // Select select = new Select(driver.findElement(By.name("destinationUnlocode"))); // select.selectByVisibleText(destination); // } // // public CargoDetailsPage book() { // driver.findElement(By.name("originUnlocode")).submit(); // // return new CargoDetailsPage(driver); // } // // public void selectArrivalDeadline(LocalDate arrivalDeadline) { // WebElement datePicker = driver.findElement(By.id("arrivalDeadline")); // datePicker.clear(); // datePicker.sendKeys(arrivalDeadline.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"))); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoDestinationPage.java // public class CargoDestinationPage { // private final WebDriver driver; // // public CargoDestinationPage(WebDriver driver) { // this.driver = driver; // WebElement cargoDestinationHeader = driver.findElement(By.cssSelector("table caption")); // // assertTrue(cargoDestinationHeader.getText().startsWith("Change destination for cargo ")); // } // // public CargoDetailsPage selectDestinationTo(String destination) { // WebElement destinationPicker = driver.findElement(By.name("unlocode")); // Select select = new Select(destinationPicker); // select.selectByVisibleText(destination); // // destinationPicker.submit(); // // return new CargoDetailsPage(driver); // } // } // // Path: src/test/java/se/citerus/dddsample/acceptance/pages/CargoDetailsPage.java // public class CargoDetailsPage { // public static final String TRACKING_ID_HEADER = "Details for cargo "; // private final WebDriver driver; // private String trackingId; // // public CargoDetailsPage(WebDriver driver) { // this.driver = driver; // // WebElement newCargoTableCaption = driver.findElement(By.cssSelector("table caption")); // // assertTrue(newCargoTableCaption.getText().startsWith(TRACKING_ID_HEADER)); // trackingId = newCargoTableCaption.getText().replaceFirst(TRACKING_ID_HEADER, ""); // } // // public String getTrackingId() { // return trackingId; // } // // public AdminPage listAllCargo() { // driver.findElement(By.linkText("List all cargos")).click(); // // return new AdminPage(driver); // } // // public void expectOriginOf(String expectedOrigin) { // String actualOrigin = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[1]/td[2]")).getText(); // // assertEquals(expectedOrigin, actualOrigin); // } // // public void expectDestinationOf(String expectedDestination) { // String actualDestination = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[2]/td[2]")).getText(); // // assertEquals(expectedDestination, actualDestination); // } // // public CargoDestinationPage changeDestination() { // driver.findElement(By.linkText("Change destination")).click(); // // return new CargoDestinationPage(driver); // } // // public void expectArrivalDeadlineOf(LocalDate expectedArrivalDeadline) { // String actualArrivalDeadline = driver.findElement(By.xpath("//div[@id='container']/table/tbody/tr[4]/td[2]")).getText(); // // assertEquals(expectedArrivalDeadline.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")), actualArrivalDeadline); // } // } // Path: src/test/java/se/citerus/dddsample/acceptance/AdminAcceptanceTest.java import org.junit.Test; import se.citerus.dddsample.acceptance.pages.AdminPage; import se.citerus.dddsample.acceptance.pages.CargoBookingPage; import se.citerus.dddsample.acceptance.pages.CargoDestinationPage; import se.citerus.dddsample.acceptance.pages.CargoDetailsPage; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import static junit.framework.TestCase.assertTrue; package se.citerus.dddsample.acceptance; public class AdminAcceptanceTest extends AbstractAcceptanceTest { @Test public void adminSiteCargoListContainsCannedCargo() {
AdminPage page = new AdminPage(driver);
citerus/dddsample-core
src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/api/TransitEdge.java // public final class TransitEdge implements Serializable { // // private final String edge; // private final String fromNode; // private final String toNode; // private final Date fromDate; // private final Date toDate; // // /** // * Constructor. // * // * @param edge // * @param fromNode // * @param toNode // * @param fromDate // * @param toDate // */ // public TransitEdge(final String edge, // final String fromNode, // final String toNode, // final Date fromDate, // final Date toDate) { // this.edge = edge; // this.fromNode = fromNode; // this.toNode = toNode; // this.fromDate = fromDate; // this.toDate = toDate; // } // // public String getEdge() { // return edge; // } // // public String getFromNode() { // return fromNode; // } // // public String getToNode() { // return toNode; // } // // public Date getFromDate() { // return fromDate; // } // // public Date getToDate() { // return toDate; // } // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.api.TransitEdge; import com.pathfinder.api.TransitPath; import java.util.*;
package com.pathfinder.internal; public class GraphTraversalServiceImpl implements GraphTraversalService { private GraphDAO dao; private Random random; private static final long ONE_MIN_MS = 1000 * 60; private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; public GraphTraversalServiceImpl(GraphDAO dao) { this.dao = dao; this.random = new Random(); } public List<TransitPath> findShortestPath(final String originNode, final String destinationNode, final Properties limitations) { Date date = nextDate(new Date()); List<String> allVertices = dao.listAllNodes(); allVertices.remove(originNode); allVertices.remove(destinationNode); final int candidateCount = getRandomNumberOfCandidates(); final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); for (int i = 0; i < candidateCount; i++) { allVertices = getRandomChunkOfNodes(allVertices);
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/api/TransitEdge.java // public final class TransitEdge implements Serializable { // // private final String edge; // private final String fromNode; // private final String toNode; // private final Date fromDate; // private final Date toDate; // // /** // * Constructor. // * // * @param edge // * @param fromNode // * @param toNode // * @param fromDate // * @param toDate // */ // public TransitEdge(final String edge, // final String fromNode, // final String toNode, // final Date fromDate, // final Date toDate) { // this.edge = edge; // this.fromNode = fromNode; // this.toNode = toNode; // this.fromDate = fromDate; // this.toDate = toDate; // } // // public String getEdge() { // return edge; // } // // public String getFromNode() { // return fromNode; // } // // public String getToNode() { // return toNode; // } // // public Date getFromDate() { // return fromDate; // } // // public Date getToDate() { // return toDate; // } // } // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.api.TransitEdge; import com.pathfinder.api.TransitPath; import java.util.*; package com.pathfinder.internal; public class GraphTraversalServiceImpl implements GraphTraversalService { private GraphDAO dao; private Random random; private static final long ONE_MIN_MS = 1000 * 60; private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; public GraphTraversalServiceImpl(GraphDAO dao) { this.dao = dao; this.random = new Random(); } public List<TransitPath> findShortestPath(final String originNode, final String destinationNode, final Properties limitations) { Date date = nextDate(new Date()); List<String> allVertices = dao.listAllNodes(); allVertices.remove(originNode); allVertices.remove(destinationNode); final int candidateCount = getRandomNumberOfCandidates(); final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); for (int i = 0; i < candidateCount; i++) { allVertices = getRandomChunkOfNodes(allVertices);
final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1);
citerus/dddsample-core
src/main/java/com/pathfinder/config/PathfinderApplicationContext.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package com.pathfinder.config; @Configuration public class PathfinderApplicationContext {
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/main/java/com/pathfinder/config/PathfinderApplicationContext.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package com.pathfinder.config; @Configuration public class PathfinderApplicationContext {
private GraphDAO graphDAO() {
citerus/dddsample-core
src/main/java/com/pathfinder/config/PathfinderApplicationContext.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() {
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/main/java/com/pathfinder/config/PathfinderApplicationContext.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() {
return new GraphDAOStub();
citerus/dddsample-core
src/main/java/com/pathfinder/config/PathfinderApplicationContext.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() { return new GraphDAOStub(); } @Bean
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/main/java/com/pathfinder/config/PathfinderApplicationContext.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() { return new GraphDAOStub(); } @Bean
public GraphTraversalService graphTraversalService() {
citerus/dddsample-core
src/main/java/com/pathfinder/config/PathfinderApplicationContext.java
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // }
import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration;
package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() { return new GraphDAOStub(); } @Bean public GraphTraversalService graphTraversalService() {
// Path: src/main/java/com/pathfinder/api/GraphTraversalService.java // public interface GraphTraversalService extends Remote { // // /** // * @param origin origin point // * @param destination destination point // * @param limitations restrictions on the path selection, as key-value according to some API specification // * @return A list of transit paths // * @throws java.rmi.RemoteException RMI problem // */ // List<TransitPath> findShortestPath(String origin, // String destination, // Properties limitations); // // } // // Path: src/main/java/com/pathfinder/internal/GraphDAO.java // public interface GraphDAO { // List<String> listAllNodes(); // String getTransitEdge(String from, String to); // } // // Path: src/main/java/com/pathfinder/internal/GraphDAOStub.java // public class GraphDAOStub implements GraphDAO{ // // private static final Random random = new Random(); // // public List<String> listAllNodes() { // return new ArrayList<String>(Arrays.asList( // "CNHKG", "AUMEL", "SESTO", "FIHEL", "USCHI", "JNTKO", "DEHAM", "CNSHA", "NLRTM", "SEGOT", "CNHGH", "USNYC", "USDAL" // )); // } // // public String getTransitEdge(String from, String to) { // final int i = random.nextInt(5); // if (i == 0) return "0100S"; // if (i == 1) return "0200T"; // if (i == 2) return "0300A"; // if (i == 3) return "0301S"; // return "0400S"; // } // // } // // Path: src/main/java/com/pathfinder/internal/GraphTraversalServiceImpl.java // public class GraphTraversalServiceImpl implements GraphTraversalService { // // private GraphDAO dao; // private Random random; // private static final long ONE_MIN_MS = 1000 * 60; // private static final long ONE_DAY_MS = ONE_MIN_MS * 60 * 24; // // public GraphTraversalServiceImpl(GraphDAO dao) { // this.dao = dao; // this.random = new Random(); // } // // public List<TransitPath> findShortestPath(final String originNode, // final String destinationNode, // final Properties limitations) { // Date date = nextDate(new Date()); // // List<String> allVertices = dao.listAllNodes(); // allVertices.remove(originNode); // allVertices.remove(destinationNode); // // final int candidateCount = getRandomNumberOfCandidates(); // final List<TransitPath> candidates = new ArrayList<TransitPath>(candidateCount); // // for (int i = 0; i < candidateCount; i++) { // allVertices = getRandomChunkOfNodes(allVertices); // final List<TransitEdge> transitEdges = new ArrayList<TransitEdge>(allVertices.size() - 1); // final String firstLegTo = allVertices.get(0); // // Date fromDate = nextDate(date); // Date toDate = nextDate(fromDate); // date = nextDate(toDate); // // transitEdges.add(new TransitEdge( // dao.getTransitEdge(originNode, firstLegTo), // originNode, firstLegTo, fromDate, toDate)); // // for (int j = 0; j < allVertices.size() - 1; j++) { // final String curr = allVertices.get(j); // final String next = allVertices.get(j + 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // date = nextDate(toDate); // transitEdges.add(new TransitEdge(dao.getTransitEdge(curr, next), curr, next, fromDate, toDate)); // } // // final String lastLegFrom = allVertices.get(allVertices.size() - 1); // fromDate = nextDate(date); // toDate = nextDate(fromDate); // transitEdges.add(new TransitEdge( // dao.getTransitEdge(lastLegFrom, destinationNode), // lastLegFrom, destinationNode, fromDate, toDate)); // // candidates.add(new TransitPath(transitEdges)); // } // // return candidates; // } // // private Date nextDate(Date date) { // return new Date(date.getTime() + ONE_DAY_MS + (random.nextInt(1000) - 500) * ONE_MIN_MS); // } // // private int getRandomNumberOfCandidates() { // return 3 + random.nextInt(3); // } // // private List<String> getRandomChunkOfNodes(List<String> allNodes) { // Collections.shuffle(allNodes); // final int total = allNodes.size(); // final int chunk = total > 4 ? 1 + new Random().nextInt(5) : total; // return allNodes.subList(0, chunk); // } // // } // Path: src/main/java/com/pathfinder/config/PathfinderApplicationContext.java import com.pathfinder.api.GraphTraversalService; import com.pathfinder.internal.GraphDAO; import com.pathfinder.internal.GraphDAOStub; import com.pathfinder.internal.GraphTraversalServiceImpl; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; package com.pathfinder.config; @Configuration public class PathfinderApplicationContext { private GraphDAO graphDAO() { return new GraphDAOStub(); } @Bean public GraphTraversalService graphTraversalService() {
return new GraphTraversalServiceImpl(graphDAO());
citerus/dddsample-core
src/main/java/se/citerus/dddsample/interfaces/booking/web/CargoAdminController.java
// Path: src/main/java/se/citerus/dddsample/interfaces/booking/facade/BookingServiceFacade.java // public interface BookingServiceFacade { // // String bookNewCargo(String origin, String destination, Date arrivalDeadline) throws RemoteException; // // CargoRoutingDTO loadCargoForRouting(String trackingId) throws RemoteException; // // void assignCargoToRoute(String trackingId, RouteCandidateDTO route) throws RemoteException; // // void changeDestination(String trackingId, String destinationUnLocode) throws RemoteException; // // List<RouteCandidateDTO> requestPossibleRoutesForCargo(String trackingId) throws RemoteException; // // List<LocationDTO> listShippingLocations() throws RemoteException; // // List<CargoRoutingDTO> listAllCargos() throws RemoteException; // // }
import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.citerus.dddsample.interfaces.booking.facade.BookingServiceFacade; import se.citerus.dddsample.interfaces.booking.facade.dto.CargoRoutingDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.LegDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.LocationDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.RouteCandidateDTO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map;
package se.citerus.dddsample.interfaces.booking.web; /** * Handles cargo booking and routing. Operates against a dedicated remoting service facade, * and could easily be rewritten as a thick Swing client. Completely separated from the domain layer, * unlike the tracking user interface. * <p> * In order to successfully keep the domain model shielded from user interface considerations, * this approach is generally preferred to the one taken in the tracking controller. However, * there is never any one perfect solution for all situations, so we've chosen to demonstrate * two polarized ways to build user interfaces. * * @see se.citerus.dddsample.interfaces.tracking.CargoTrackingController */ @Controller @RequestMapping("/admin") public final class CargoAdminController {
// Path: src/main/java/se/citerus/dddsample/interfaces/booking/facade/BookingServiceFacade.java // public interface BookingServiceFacade { // // String bookNewCargo(String origin, String destination, Date arrivalDeadline) throws RemoteException; // // CargoRoutingDTO loadCargoForRouting(String trackingId) throws RemoteException; // // void assignCargoToRoute(String trackingId, RouteCandidateDTO route) throws RemoteException; // // void changeDestination(String trackingId, String destinationUnLocode) throws RemoteException; // // List<RouteCandidateDTO> requestPossibleRoutesForCargo(String trackingId) throws RemoteException; // // List<LocationDTO> listShippingLocations() throws RemoteException; // // List<CargoRoutingDTO> listAllCargos() throws RemoteException; // // } // Path: src/main/java/se/citerus/dddsample/interfaces/booking/web/CargoAdminController.java import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import se.citerus.dddsample.interfaces.booking.facade.BookingServiceFacade; import se.citerus.dddsample.interfaces.booking.facade.dto.CargoRoutingDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.LegDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.LocationDTO; import se.citerus.dddsample.interfaces.booking.facade.dto.RouteCandidateDTO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; package se.citerus.dddsample.interfaces.booking.web; /** * Handles cargo booking and routing. Operates against a dedicated remoting service facade, * and could easily be rewritten as a thick Swing client. Completely separated from the domain layer, * unlike the tracking user interface. * <p> * In order to successfully keep the domain model shielded from user interface considerations, * this approach is generally preferred to the one taken in the tracking controller. However, * there is never any one perfect solution for all situations, so we've chosen to demonstrate * two polarized ways to build user interfaces. * * @see se.citerus.dddsample.interfaces.tracking.CargoTrackingController */ @Controller @RequestMapping("/admin") public final class CargoAdminController {
private BookingServiceFacade bookingServiceFacade;
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreesActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // }
import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.shaunchurch.androidpickings.ui.trees; public class TreesActivity extends BaseActivity { private TreesComponent treesComponent; @Inject TreeAdapter treeAdapter; @Inject TreeSupplier treeSupplier; @InjectView(R.id.listTrees) ListView listView; @Override
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreesActivity.java import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.shaunchurch.androidpickings.ui.trees; public class TreesActivity extends BaseActivity { private TreesComponent treesComponent; @Inject TreeAdapter treeAdapter; @Inject TreeSupplier treeSupplier; @InjectView(R.id.listTrees) ListView listView; @Override
protected void onCreateComponent(AppComponent appComponent) {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // }
import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.shaunchurch.androidpickings.ui.planets; public class PlanetsActivity extends BaseActivity implements PlanetView { private PlanetsComponent planetsComponent; @Inject PlanetPresenter presenter; @Inject PlanetAdapter planetAdapter; @InjectView(R.id.listPlanets) ListView listPlanets; @Override
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsActivity.java import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.shaunchurch.androidpickings.ui.planets; public class PlanetsActivity extends BaseActivity implements PlanetView { private PlanetsComponent planetsComponent; @Inject PlanetPresenter presenter; @Inject PlanetAdapter planetAdapter; @InjectView(R.id.listPlanets) ListView listPlanets; @Override
protected void onCreateComponent(AppComponent appComponent) {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // }
import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.shaunchurch.androidpickings.ui.planets; public class PlanetsActivity extends BaseActivity implements PlanetView { private PlanetsComponent planetsComponent; @Inject PlanetPresenter presenter; @Inject PlanetAdapter planetAdapter; @InjectView(R.id.listPlanets) ListView listPlanets; @Override protected void onCreateComponent(AppComponent appComponent) { planetsComponent = DaggerPlanetsComponent.builder() .appComponent(appComponent) .planetsModule(new PlanetsModule(this)) .build(); planetsComponent.inject(this); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_planets); ButterKnife.inject(this); // set list adapter listPlanets.setAdapter(planetAdapter); } @Override
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsActivity.java import android.os.Bundle; import android.widget.ListView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import java.util.List; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.shaunchurch.androidpickings.ui.planets; public class PlanetsActivity extends BaseActivity implements PlanetView { private PlanetsComponent planetsComponent; @Inject PlanetPresenter presenter; @Inject PlanetAdapter planetAdapter; @InjectView(R.id.listPlanets) ListView listPlanets; @Override protected void onCreateComponent(AppComponent appComponent) { planetsComponent = DaggerPlanetsComponent.builder() .appComponent(appComponent) .planetsModule(new PlanetsModule(this)) .build(); planetsComponent.inject(this); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_planets); ButterKnife.inject(this); // set list adapter listPlanets.setAdapter(planetAdapter); } @Override
public void onPlanetsReceived(List<Planet> planets) {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardComponent.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // }
import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Component;
package com.shaunchurch.androidpickings.ui.dashboard; @DashboardScope @Component(
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardComponent.java import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Component; package com.shaunchurch.androidpickings.ui.dashboard; @DashboardScope @Component(
dependencies = AppComponent.class,
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardComponent.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // }
import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Component;
package com.shaunchurch.androidpickings.ui.dashboard; @DashboardScope @Component( dependencies = AppComponent.class, modules = DashboardModule.class ) public interface DashboardComponent { void inject(DashboardActivity activity);
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardComponent.java import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Component; package com.shaunchurch.androidpickings.ui.dashboard; @DashboardScope @Component( dependencies = AppComponent.class, modules = DashboardModule.class ) public interface DashboardComponent { void inject(DashboardActivity activity);
Vehicle provideVehicle();
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardModule.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/example/Motor.java // public class Motor { // private int rpm; // // public Motor() { // this.rpm = 0; // } // // public int getRpm(){ // return rpm; // } // // public void accelerate(int value){ // rpm = rpm + value; // } // // public void brake(){ // rpm = 0; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // }
import com.shaunchurch.androidpickings.example.Motor; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Module; import dagger.Provides;
package com.shaunchurch.androidpickings.ui.dashboard; @Module public class DashboardModule { @Provides @DashboardScope
// Path: app/src/main/java/com/shaunchurch/androidpickings/example/Motor.java // public class Motor { // private int rpm; // // public Motor() { // this.rpm = 0; // } // // public int getRpm(){ // return rpm; // } // // public void accelerate(int value){ // rpm = rpm + value; // } // // public void brake(){ // rpm = 0; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardModule.java import com.shaunchurch.androidpickings.example.Motor; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Module; import dagger.Provides; package com.shaunchurch.androidpickings.ui.dashboard; @Module public class DashboardModule { @Provides @DashboardScope
Vehicle provideVehicle() {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardModule.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/example/Motor.java // public class Motor { // private int rpm; // // public Motor() { // this.rpm = 0; // } // // public int getRpm(){ // return rpm; // } // // public void accelerate(int value){ // rpm = rpm + value; // } // // public void brake(){ // rpm = 0; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // }
import com.shaunchurch.androidpickings.example.Motor; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Module; import dagger.Provides;
package com.shaunchurch.androidpickings.ui.dashboard; @Module public class DashboardModule { @Provides @DashboardScope Vehicle provideVehicle() {
// Path: app/src/main/java/com/shaunchurch/androidpickings/example/Motor.java // public class Motor { // private int rpm; // // public Motor() { // this.rpm = 0; // } // // public int getRpm(){ // return rpm; // } // // public void accelerate(int value){ // rpm = rpm + value; // } // // public void brake(){ // rpm = 0; // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/example/Vehicle.java // public class Vehicle { // // private Motor motor; // // @Inject // public Vehicle(Motor motor){ // this.motor = motor; // } // // public void increaseSpeed(int value){ // motor.accelerate(value); // } // // public void stop(){ // motor.brake(); // } // // public int getSpeed(){ // return motor.getRpm(); // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/dashboard/DashboardModule.java import com.shaunchurch.androidpickings.example.Motor; import com.shaunchurch.androidpickings.example.Vehicle; import dagger.Module; import dagger.Provides; package com.shaunchurch.androidpickings.ui.dashboard; @Module public class DashboardModule { @Provides @DashboardScope Vehicle provideVehicle() {
return new Vehicle(new Motor());
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/hello/HelloComponent.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // }
import com.shaunchurch.androidpickings.AppComponent; import dagger.Component;
package com.shaunchurch.androidpickings.ui.hello; @HelloScope @Component(
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/hello/HelloComponent.java import com.shaunchurch.androidpickings.AppComponent; import dagger.Component; package com.shaunchurch.androidpickings.ui.hello; @HelloScope @Component(
dependencies = AppComponent.class,
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreesComponent.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // }
import com.shaunchurch.androidpickings.AppComponent; import dagger.Component;
package com.shaunchurch.androidpickings.ui.trees; @TreesScope @Component(
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreesComponent.java import com.shaunchurch.androidpickings.AppComponent; import dagger.Component; package com.shaunchurch.androidpickings.ui.trees; @TreesScope @Component(
dependencies = AppComponent.class,
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetAdapter.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // }
import android.app.Application; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import java.util.Collections; import java.util.List; import javax.inject.Inject;
package com.shaunchurch.androidpickings.ui.planets; public class PlanetAdapter extends BaseAdapter { private Context context; private PlanetSupplier planetSupplier;
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Planet.java // public class Planet { // // private String name; // private String type; // // public Planet(String name, String type) { // this.name = name; // this.type = type; // } // // public String getName() { // return name; // } // // public String getType() { // return type; // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetAdapter.java import android.app.Application; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.data.entities.Planet; import java.util.Collections; import java.util.List; import javax.inject.Inject; package com.shaunchurch.androidpickings.ui.planets; public class PlanetAdapter extends BaseAdapter { private Context context; private PlanetSupplier planetSupplier;
private List<Planet> planets = Collections.emptyList();
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreeItemPresenter.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Tree.java // public class Tree { // public String name; // // public Tree() { // } // // public void setName(String name) { // this.name = name; // } // }
import android.view.View; import com.shaunchurch.androidpickings.data.entities.Tree; import java.util.List;
package com.shaunchurch.androidpickings.ui.trees; public interface TreeItemPresenter { /** * Returns the resource id of the layout that represents the class that * implements this interface * * @return */ int provideLayoutRes(); /** * This method is called after a View has been inflated and is simply used * to display the wanted info for that inflated View * * @param view * View that has been inflated * @param position * Position of the element we are displaying */ void display(View view, int position);
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Tree.java // public class Tree { // public String name; // // public Tree() { // } // // public void setName(String name) { // this.name = name; // } // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/trees/TreeItemPresenter.java import android.view.View; import com.shaunchurch.androidpickings.data.entities.Tree; import java.util.List; package com.shaunchurch.androidpickings.ui.trees; public interface TreeItemPresenter { /** * Returns the resource id of the layout that represents the class that * implements this interface * * @return */ int provideLayoutRes(); /** * This method is called after a View has been inflated and is simply used * to display the wanted info for that inflated View * * @param view * View that has been inflated * @param position * Position of the element we are displaying */ void display(View view, int position);
void setItem(Tree tree);
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/common/WebImageView.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Image.java // public class Image { // public String link; // }
import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import com.shaunchurch.androidpickings.data.entities.Image; import com.squareup.picasso.Picasso; import javax.inject.Inject;
package com.shaunchurch.androidpickings.ui.common; public class WebImageView extends ImageView { @Inject Picasso picasso; public WebImageView(Context context, AttributeSet attrs) { super(context, attrs); this.picasso = picasso; // ((HasComponent<Injector>) context).getComponent().inject(this); }
// Path: app/src/main/java/com/shaunchurch/androidpickings/data/entities/Image.java // public class Image { // public String link; // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/common/WebImageView.java import android.content.Context; import android.util.AttributeSet; import android.widget.ImageView; import com.shaunchurch.androidpickings.data.entities.Image; import com.squareup.picasso.Picasso; import javax.inject.Inject; package com.shaunchurch.androidpickings.ui.common; public class WebImageView extends ImageView { @Inject Picasso picasso; public WebImageView(Context context, AttributeSet attrs) { super(context, attrs); this.picasso = picasso; // ((HasComponent<Injector>) context).getComponent().inject(this); }
public void bindTo(Image image) {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject;
package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject; package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject
AppContainer appContainer;
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject;
package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject AppContainer appContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject; package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject AppContainer appContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
App app = App.get(this);
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // }
import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject;
package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject AppContainer appContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); App app = App.get(this); onCreateComponent(app.component()); if(appContainer == null ){ throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); } } /** * Must be implemented by derived activities. * Otherwise IllegalStateException will be thrown. * Derived activity is responsible to store and save it's component. */
// Path: app/src/main/java/com/shaunchurch/androidpickings/App.java // public class App extends Application { // // private AppComponent component; // // @Override // public void onCreate() { // super.onCreate(); // // if(BuildConfig.DEBUG) { // Timber.plant(new Timber.DebugTree()); // } // // buildComponentAndInject(); // } // // /** // * Initialize our root AppComponent, kick off our dependency resolutions // */ // public void buildComponentAndInject() { // component = AppComponent.Initializer.init(this); // component.inject(this); // } // // public AppComponent component() { // return component; // } // // public static App get(Context context) { // return (App) context.getApplicationContext(); // } // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import com.shaunchurch.androidpickings.App; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.ui.AppContainer; import javax.inject.Inject; package com.shaunchurch.androidpickings.ui.base; public abstract class BaseActivity extends ActionBarActivity { @Inject AppContainer appContainer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); App app = App.get(this); onCreateComponent(app.component()); if(appContainer == null ){ throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); } } /** * Must be implemented by derived activities. * Otherwise IllegalStateException will be thrown. * Derived activity is responsible to store and save it's component. */
protected abstract void onCreateComponent(AppComponent appComponent);
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/hello/HelloActivity.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // }
import android.os.Bundle; import android.widget.TextView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView;
package com.shaunchurch.androidpickings.ui.hello; public class HelloActivity extends BaseActivity implements HelloView { // component private HelloComponent helloComponent; // dependencies @Inject HelloPresenter presenter; // views @InjectView(R.id.textMessage) TextView textMessage; @Override
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/base/BaseActivity.java // public abstract class BaseActivity extends ActionBarActivity { // // @Inject // AppContainer appContainer; // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // App app = App.get(this); // onCreateComponent(app.component()); // // if(appContainer == null ){ // throw new IllegalStateException("No injection happened. Add component.inject(this) in onCreateComponent."); // } // } // // /** // * Must be implemented by derived activities. // * Otherwise IllegalStateException will be thrown. // * Derived activity is responsible to store and save it's component. // */ // protected abstract void onCreateComponent(AppComponent appComponent); // // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/hello/HelloActivity.java import android.os.Bundle; import android.widget.TextView; import com.shaunchurch.androidpickings.AppComponent; import com.shaunchurch.androidpickings.R; import com.shaunchurch.androidpickings.ui.base.BaseActivity; import javax.inject.Inject; import butterknife.ButterKnife; import butterknife.InjectView; package com.shaunchurch.androidpickings.ui.hello; public class HelloActivity extends BaseActivity implements HelloView { // component private HelloComponent helloComponent; // dependencies @Inject HelloPresenter presenter; // views @InjectView(R.id.textMessage) TextView textMessage; @Override
protected void onCreateComponent(AppComponent appComponent) {
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsComponent.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // }
import com.shaunchurch.androidpickings.AppComponent; import dagger.Component;
package com.shaunchurch.androidpickings.ui.planets; @PlanetsScope @Component(
// Path: app/src/main/java/com/shaunchurch/androidpickings/AppComponent.java // @ApplicationScope // @Component(modules = { AppModule.class, UiModule.class, DataModule.class }) // public interface AppComponent extends AppGraph { // /** // * An initializer that creates the graph from an application. // */ // final static class Initializer { // static AppComponent init(App app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .build(); // } // private Initializer() {} // No instances. // } // // Application provideApplication(); // } // Path: app/src/main/java/com/shaunchurch/androidpickings/ui/planets/PlanetsComponent.java import com.shaunchurch.androidpickings.AppComponent; import dagger.Component; package com.shaunchurch.androidpickings.ui.planets; @PlanetsScope @Component(
dependencies = AppComponent.class,
shaunchurch/AndroidPickings
app/src/main/java/com/shaunchurch/androidpickings/AppGraph.java
// Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // }
import com.shaunchurch.androidpickings.ui.AppContainer; import com.squareup.picasso.Picasso;
package com.shaunchurch.androidpickings; /** * A common interface (which can be) implemented by both the Release and Debug flavored components. */ public interface AppGraph { void inject(App app);
// Path: app/src/main/java/com/shaunchurch/androidpickings/ui/AppContainer.java // public interface AppContainer { // /** // * The root {@link android.view.ViewGroup} into which the activity should place its contents. // */ // ViewGroup get(Activity activity); // // /** // * An {@link AppContainer} which returns the normal activity content view. // */ // AppContainer DEFAULT = new AppContainer() { // @Override // public ViewGroup get(Activity activity) { // return findById(activity, android.R.id.content); // } // }; // } // Path: app/src/main/java/com/shaunchurch/androidpickings/AppGraph.java import com.shaunchurch.androidpickings.ui.AppContainer; import com.squareup.picasso.Picasso; package com.shaunchurch.androidpickings; /** * A common interface (which can be) implemented by both the Release and Debug flavored components. */ public interface AppGraph { void inject(App app);
AppContainer appContainer();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/capture/api/dto/executions/ExecutionResponse.java
// Path: src/main/java/com/frameworkium/core/api/dto/AbstractDTO.java // public abstract class AbstractDTO<T> implements Serializable, Cloneable { // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // @SuppressWarnings("unchecked") // protected T clone() throws CloneNotSupportedException { // try { // return (T) SerializationUtils.clone(this); // } catch (Exception e) { // throw new CloneNotSupportedException(e.getMessage()); // } // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString( // this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // }
import com.frameworkium.core.api.dto.AbstractDTO; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import java.util.List;
package com.frameworkium.integration.capture.api.dto.executions; public class ExecutionResponse extends AbstractDTO<ExecutionResponse> { public String testID; public Browser browser; public SoftwareUnderTest softwareUnderTest; public String nodeAddress; public String created; public String lastUpdated; public String currentStatus; public String executionID;
// Path: src/main/java/com/frameworkium/core/api/dto/AbstractDTO.java // public abstract class AbstractDTO<T> implements Serializable, Cloneable { // // @Override // public int hashCode() { // return HashCodeBuilder.reflectionHashCode(this); // } // // @Override // public boolean equals(Object obj) { // return EqualsBuilder.reflectionEquals(this, obj); // } // // @Override // @SuppressWarnings("unchecked") // protected T clone() throws CloneNotSupportedException { // try { // return (T) SerializationUtils.clone(this); // } catch (Exception e) { // throw new CloneNotSupportedException(e.getMessage()); // } // } // // @Override // public String toString() { // return ReflectionToStringBuilder.toString( // this, ToStringStyle.SHORT_PREFIX_STYLE); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // Path: src/test/java/com/frameworkium/integration/capture/api/dto/executions/ExecutionResponse.java import com.frameworkium.core.api.dto.AbstractDTO; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import java.util.List; package com.frameworkium.integration.capture.api.dto.executions; public class ExecutionResponse extends AbstractDTO<ExecutionResponse> { public String testID; public Browser browser; public SoftwareUnderTest softwareUnderTest; public String nodeAddress; public String created; public String lastUpdated; public String currentStatus; public String executionID;
public List<Screenshot> screenshots;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/frameworkium/pages/JQueryDemoPage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.ExtraExpectedConditions; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy;
package com.frameworkium.integration.frameworkium.pages; public class JQueryDemoPage extends BasePage<JQueryDemoPage> { @Visible @FindBy(css = "#content > h1") private WebElement heading; public static JQueryDemoPage open() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/frameworkium/pages/JQueryDemoPage.java import com.frameworkium.core.ui.ExtraExpectedConditions; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; package com.frameworkium.integration.frameworkium.pages; public class JQueryDemoPage extends BasePage<JQueryDemoPage> { @Visible @FindBy(css = "#content > h1") private WebElement heading; public static JQueryDemoPage open() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/core/ui/ExtraExpectedConditionsTest.java
// Path: src/main/java/com/frameworkium/core/ui/element/StreamTable.java // public class StreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream().filter(WebElement::isDisplayed); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream().filter(WebElement::isDisplayed); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // }
import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.element.StreamTable; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List;
package com.frameworkium.core.ui; /** * Tests to ensure elements other than just WebElements can be passed into * {@link ExtraExpectedConditions}. * * These tests do not check the correctness of the implementation, they are here * to prevent https://github.com/Frameworkium/frameworkium-core/issues/133 */ public class ExtraExpectedConditionsTest { private List<Link> links = new ArrayList<>();
// Path: src/main/java/com/frameworkium/core/ui/element/StreamTable.java // public class StreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream().filter(WebElement::isDisplayed); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream().filter(WebElement::isDisplayed); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // Path: src/test/java/com/frameworkium/core/ui/ExtraExpectedConditionsTest.java import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.element.StreamTable; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.List; package com.frameworkium.core.ui; /** * Tests to ensure elements other than just WebElements can be passed into * {@link ExtraExpectedConditions}. * * These tests do not check the correctness of the implementation, they are here * to prevent https://github.com/Frameworkium/frameworkium-core/issues/133 */ public class ExtraExpectedConditionsTest { private List<Link> links = new ArrayList<>();
private List<StreamTable> tables = new ArrayList<>();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NotFoundException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.function.Predicate; import java.util.stream.Stream;
package com.frameworkium.integration.wikipedia.pages; /** * This page uses OptimisedStreamTable, this is slower than using Lists of * WebElements for columns, especially when running over a grid due to the far * greater number of page lookups required. This is even worse for StreamTable, * but StreamTable copes with a wider variety of Tables. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are likely to change often. */ public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { @Visible @CacheLookup @FindBy(css = "table.wikitable") // luckily there's only one
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NotFoundException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.function.Predicate; import java.util.stream.Stream; package com.frameworkium.integration.wikipedia.pages; /** * This page uses OptimisedStreamTable, this is slower than using Lists of * WebElements for columns, especially when running over a grid due to the far * greater number of page lookups required. This is even worse for StreamTable, * but StreamTable copes with a wider variety of Tables. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are likely to change often. */ public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { @Visible @CacheLookup @FindBy(css = "table.wikitable") // luckily there's only one
private OptimisedStreamTable listTable;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NotFoundException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.function.Predicate; import java.util.stream.Stream;
package com.frameworkium.integration.wikipedia.pages; /** * This page uses OptimisedStreamTable, this is slower than using Lists of * WebElements for columns, especially when running over a grid due to the far * greater number of page lookups required. This is even worse for StreamTable, * but StreamTable copes with a wider variety of Tables. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are likely to change often. */ public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { @Visible @CacheLookup @FindBy(css = "table.wikitable") // luckily there's only one private OptimisedStreamTable listTable; public static EnglishCountiesPage open() {
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NotFoundException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.function.Predicate; import java.util.stream.Stream; package com.frameworkium.integration.wikipedia.pages; /** * This page uses OptimisedStreamTable, this is slower than using Lists of * WebElements for columns, especially when running over a grid due to the far * greater number of page lookups required. This is even worse for StreamTable, * but StreamTable copes with a wider variety of Tables. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are likely to change often. */ public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { @Visible @CacheLookup @FindBy(css = "table.wikitable") // luckily there's only one private OptimisedStreamTable listTable; public static EnglishCountiesPage open() {
return PageFactory.newInstance(EnglishCountiesPage.class,
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/common/reporting/jira/service/Project.java
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/project/ProjectDto.java // public class ProjectDto extends AbstractDTO<ProjectDto> { // @JsonSerialize(using = ToStringSerializer.class) // public Long id; // public String key; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/version/VersionDto.java // @JsonDeserialize(builder = VersionDto.Builder.class) // public class VersionDto extends AbstractDTO<VersionDto> { // public final String self; // public final Long id; // public final String description; // public final String name; // public final Boolean archived; // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") // public final LocalDate releaseDate; // public final Boolean released; // public final Boolean overdue; // public final LocalDate userReleaseDate; // public final String project; // public final Long projectId; // // private VersionDto(final Builder builder) { // self = builder.self; // id = builder.id; // description = builder.description; // name = builder.name; // archived = builder.archived; // released = builder.released; // releaseDate = builder.releaseDate; // overdue = builder.overdue; // userReleaseDate = builder.userReleaseDate; // project = builder.project; // projectId = builder.projectId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // private String self; // @JsonSerialize(as = String.class) // private Long id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // private LocalDate releaseDate; // private Boolean overdue; // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MMM/yy", // with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_VALUES) // private LocalDate userReleaseDate; // private String project; // private Long projectId; // // private Builder() { // } // // public Builder self(final String self) { // this.self = self; // return this; // } // // public Builder id(final Long id) { // this.id = id; // return this; // } // // public Builder description(final String description) { // this.description = description; // return this; // } // // public Builder name(final String name) { // this.name = name; // return this; // } // // public Builder archived(final Boolean archived) { // this.archived = archived; // return this; // } // // public Builder released(final Boolean released) { // this.released = released; // return this; // } // // public Builder releaseDate(final LocalDate releaseDate) { // this.releaseDate = releaseDate; // return this; // } // // public Builder overdue(final Boolean overdue) { // this.overdue = overdue; // return this; // } // // public Builder userReleaseDate(final LocalDate userReleaseDate) { // this.userReleaseDate = userReleaseDate; // return this; // } // // public Builder project(final String project) { // this.project = project; // return this; // } // // public Builder projectId(final Long projectId) { // this.projectId = projectId; // return this; // } // // public VersionDto build() { // return new VersionDto(this); // } // } // }
import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.project.ProjectDto; import com.frameworkium.core.common.reporting.jira.dto.version.VersionDto; import com.frameworkium.core.common.reporting.jira.endpoint.JiraEndpoint; import io.restassured.http.ContentType; import java.util.List;
package com.frameworkium.core.common.reporting.jira.service; public class Project extends AbstractJiraService { public ProjectDto getProject(String projectIdOrKey) { return getRequestSpec() .basePath(JiraEndpoint.PROJECT.getUrl()) .pathParam("projectIdOrKey", projectIdOrKey) .contentType(ContentType.JSON) .get("/{projectIdOrKey}") .then() .log().ifValidationFails() .statusCode(SC_OK) .extract() .as(ProjectDto.class); }
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/project/ProjectDto.java // public class ProjectDto extends AbstractDTO<ProjectDto> { // @JsonSerialize(using = ToStringSerializer.class) // public Long id; // public String key; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/version/VersionDto.java // @JsonDeserialize(builder = VersionDto.Builder.class) // public class VersionDto extends AbstractDTO<VersionDto> { // public final String self; // public final Long id; // public final String description; // public final String name; // public final Boolean archived; // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") // public final LocalDate releaseDate; // public final Boolean released; // public final Boolean overdue; // public final LocalDate userReleaseDate; // public final String project; // public final Long projectId; // // private VersionDto(final Builder builder) { // self = builder.self; // id = builder.id; // description = builder.description; // name = builder.name; // archived = builder.archived; // released = builder.released; // releaseDate = builder.releaseDate; // overdue = builder.overdue; // userReleaseDate = builder.userReleaseDate; // project = builder.project; // projectId = builder.projectId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // private String self; // @JsonSerialize(as = String.class) // private Long id; // private String description; // private String name; // private Boolean archived; // private Boolean released; // private LocalDate releaseDate; // private Boolean overdue; // @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MMM/yy", // with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_VALUES) // private LocalDate userReleaseDate; // private String project; // private Long projectId; // // private Builder() { // } // // public Builder self(final String self) { // this.self = self; // return this; // } // // public Builder id(final Long id) { // this.id = id; // return this; // } // // public Builder description(final String description) { // this.description = description; // return this; // } // // public Builder name(final String name) { // this.name = name; // return this; // } // // public Builder archived(final Boolean archived) { // this.archived = archived; // return this; // } // // public Builder released(final Boolean released) { // this.released = released; // return this; // } // // public Builder releaseDate(final LocalDate releaseDate) { // this.releaseDate = releaseDate; // return this; // } // // public Builder overdue(final Boolean overdue) { // this.overdue = overdue; // return this; // } // // public Builder userReleaseDate(final LocalDate userReleaseDate) { // this.userReleaseDate = userReleaseDate; // return this; // } // // public Builder project(final String project) { // this.project = project; // return this; // } // // public Builder projectId(final Long projectId) { // this.projectId = projectId; // return this; // } // // public VersionDto build() { // return new VersionDto(this); // } // } // } // Path: src/main/java/com/frameworkium/core/common/reporting/jira/service/Project.java import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.project.ProjectDto; import com.frameworkium.core.common.reporting.jira.dto.version.VersionDto; import com.frameworkium.core.common.reporting.jira.endpoint.JiraEndpoint; import io.restassured.http.ContentType; import java.util.List; package com.frameworkium.core.common.reporting.jira.service; public class Project extends AbstractJiraService { public ProjectDto getProject(String projectIdOrKey) { return getRequestSpec() .basePath(JiraEndpoint.PROJECT.getUrl()) .pathParam("projectIdOrKey", projectIdOrKey) .contentType(ContentType.JSON) .get("/{projectIdOrKey}") .then() .log().ifValidationFails() .statusCode(SC_OK) .extract() .as(ProjectDto.class); }
public List<VersionDto> getProjectVersions(String projectIdOrKey) {
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/WelcomePage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.ForceVisible; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import io.qameta.allure.Step; import org.openqa.selenium.support.FindBy; import java.time.Duration; import static java.time.temporal.ChronoUnit.SECONDS;
package com.frameworkium.integration.theinternet.pages; public class WelcomePage extends BasePage<WelcomePage> { @Visible @FindBy(linkText = "Checkboxes") private Link checkboxesLink; // ForceVisible not strictly required, just testing it doesn't error @ForceVisible @FindBy(linkText = "Drag and Drop") private Link dragAndDropLink; @FindBy(linkText = "Dynamic Loading") private Link dynamicLoadingLink; @FindBy(linkText = "Hovers") private Link hoversLink; @FindBy(linkText = "JavaScript Alerts") private Link javascriptAlertsLink; @FindBy(linkText = "Key Presses") private Link keyPressesLink; @Step("Navigate to https://the-internet.herokuapp.com") public static WelcomePage open() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/theinternet/pages/WelcomePage.java import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.ForceVisible; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import io.qameta.allure.Step; import org.openqa.selenium.support.FindBy; import java.time.Duration; import static java.time.temporal.ChronoUnit.SECONDS; package com.frameworkium.integration.theinternet.pages; public class WelcomePage extends BasePage<WelcomePage> { @Visible @FindBy(linkText = "Checkboxes") private Link checkboxesLink; // ForceVisible not strictly required, just testing it doesn't error @ForceVisible @FindBy(linkText = "Drag and Drop") private Link dragAndDropLink; @FindBy(linkText = "Dynamic Loading") private Link dynamicLoadingLink; @FindBy(linkText = "Hovers") private Link hoversLink; @FindBy(linkText = "JavaScript Alerts") private Link javascriptAlertsLink; @FindBy(linkText = "Key Presses") private Link keyPressesLink; @Step("Navigate to https://the-internet.herokuapp.com") public static WelcomePage open() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/capture/model/Browser.java
// Path: src/main/java/com/frameworkium/core/ui/UITestLifecycle.java // public class UITestLifecycle { // // private static final Duration DEFAULT_TIMEOUT = Duration.of(10, SECONDS); // // private static final ThreadLocal<ScreenshotCapture> capture = new ThreadLocal<>(); // private static final ThreadLocal<Wait<WebDriver>> wait = new ThreadLocal<>(); // private static final ThreadLocal<UITestLifecycle> uiTestLifecycle = // ThreadLocal.withInitial(UITestLifecycle::new); // // private static DriverLifecycle driverLifecycle; // private static String userAgent; // // /** // * @return a ThreadLocal instance of {@link UITestLifecycle} // */ // public static UITestLifecycle get() { // return uiTestLifecycle.get(); // } // // /** // * @return check to see if class initialised correctly. // */ // public boolean isInitialised() { // return wait.get() != null; // } // // /** // * Run this before the test suite to initialise a pool of drivers. // */ // public void beforeSuite() { // if (Property.REUSE_BROWSER.getBoolean()) { // driverLifecycle = // new MultiUseDriverLifecycle( // Property.THREADS.getIntWithDefault(1)); // } else { // driverLifecycle = new SingleUseDriverLifecycle(); // } // driverLifecycle.initDriverPool(DriverSetup::instantiateDriver); // } // // /** // * Run this before each test method to initialise the // * browser, wait, capture, and user agent. // * // * <p>This is useful for times when the testMethod does not contain the required // * test name e.g. using data providers for BDD. // * // * @param testName the test name for Capture // */ // public void beforeTestMethod(String testName) { // driverLifecycle.initBrowserBeforeTest(DriverSetup::instantiateDriver); // // wait.set(newWaitWithTimeout(DEFAULT_TIMEOUT)); // // if (ScreenshotCapture.isRequired()) { // capture.set(new ScreenshotCapture(testName)); // } // // if (userAgent == null) { // userAgent = UserAgent.getUserAgent((JavascriptExecutor) getWebDriver()); // } // } // // /** // * @param testMethod the method about to run, used to extract the test name // * @see #beforeTestMethod(String) // */ // public void beforeTestMethod(Method testMethod) { // beforeTestMethod(getTestNameForCapture(testMethod)); // } // // private String getTestNameForCapture(Method testMethod) { // Optional<String> testID = TestIdUtils.getIssueOrTmsLinkValue(testMethod); // if (!testID.isPresent() || testID.get().isEmpty()) { // testID = Optional.of(StringUtils.abbreviate(testMethod.getName(), 20)); // } // return testID.orElse("n/a"); // } // // /** // * Run after each test method to clear or tear down the browser // */ // public void afterTestMethod() { // driverLifecycle.tearDownDriver(); // } // // /** // * Run after the entire test suite to: // * clear down the browser pool, send remaining screenshots to Capture // * and create properties for Allure. // */ // public void afterTestSuite() { // driverLifecycle.tearDownDriverPool(); // ScreenshotCapture.processRemainingBacklog(); // AllureProperties.createUI(); // } // // /** // * @return new Wait with default timeout. // * @deprecated use {@code UITestLifecycle.get().getWait()} instead. // */ // @Deprecated // public Wait<WebDriver> newDefaultWait() { // return newWaitWithTimeout(DEFAULT_TIMEOUT); // } // // /** // * @param timeout timeout for the new Wait // * @return a Wait with the given timeout // */ // public Wait<WebDriver> newWaitWithTimeout(Duration timeout) { // return new FluentWait<>(getWebDriver()) // .withTimeout(timeout) // .ignoring(NoSuchElementException.class) // .ignoring(StaleElementReferenceException.class); // } // // public WebDriver getWebDriver() { // return driverLifecycle.getWebDriver(); // } // // public ScreenshotCapture getCapture() { // return capture.get(); // } // // public Wait<WebDriver> getWait() { // return wait.get(); // } // // /** // * @return the user agent of the browser in the first UI test to run. // */ // public Optional<String> getUserAgent() { // return Optional.ofNullable(userAgent); // } // // /** // * @return the session ID of the remote WebDriver // */ // public String getRemoteSessionId() { // return Objects.toString(((RemoteWebDriver) getWebDriver()).getSessionId()); // } // }
import static com.frameworkium.core.common.properties.Property.BROWSER; import static com.frameworkium.core.common.properties.Property.BROWSER_VERSION; import static com.frameworkium.core.common.properties.Property.DEVICE; import static com.frameworkium.core.common.properties.Property.PLATFORM; import static com.frameworkium.core.common.properties.Property.PLATFORM_VERSION; import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.UITestLifecycle; import com.frameworkium.core.ui.driver.DriverSetup; import java.util.Optional; import net.sf.uadetector.ReadableUserAgent; import net.sf.uadetector.UserAgentStringParser; import net.sf.uadetector.service.UADetectorServiceFactory;
package com.frameworkium.core.ui.capture.model; @JsonInclude(JsonInclude.Include.NON_NULL) public class Browser { public String name; public String version; public String device; public String platform; public String platformVersion; /** * Create browser object. */ public Browser() {
// Path: src/main/java/com/frameworkium/core/ui/UITestLifecycle.java // public class UITestLifecycle { // // private static final Duration DEFAULT_TIMEOUT = Duration.of(10, SECONDS); // // private static final ThreadLocal<ScreenshotCapture> capture = new ThreadLocal<>(); // private static final ThreadLocal<Wait<WebDriver>> wait = new ThreadLocal<>(); // private static final ThreadLocal<UITestLifecycle> uiTestLifecycle = // ThreadLocal.withInitial(UITestLifecycle::new); // // private static DriverLifecycle driverLifecycle; // private static String userAgent; // // /** // * @return a ThreadLocal instance of {@link UITestLifecycle} // */ // public static UITestLifecycle get() { // return uiTestLifecycle.get(); // } // // /** // * @return check to see if class initialised correctly. // */ // public boolean isInitialised() { // return wait.get() != null; // } // // /** // * Run this before the test suite to initialise a pool of drivers. // */ // public void beforeSuite() { // if (Property.REUSE_BROWSER.getBoolean()) { // driverLifecycle = // new MultiUseDriverLifecycle( // Property.THREADS.getIntWithDefault(1)); // } else { // driverLifecycle = new SingleUseDriverLifecycle(); // } // driverLifecycle.initDriverPool(DriverSetup::instantiateDriver); // } // // /** // * Run this before each test method to initialise the // * browser, wait, capture, and user agent. // * // * <p>This is useful for times when the testMethod does not contain the required // * test name e.g. using data providers for BDD. // * // * @param testName the test name for Capture // */ // public void beforeTestMethod(String testName) { // driverLifecycle.initBrowserBeforeTest(DriverSetup::instantiateDriver); // // wait.set(newWaitWithTimeout(DEFAULT_TIMEOUT)); // // if (ScreenshotCapture.isRequired()) { // capture.set(new ScreenshotCapture(testName)); // } // // if (userAgent == null) { // userAgent = UserAgent.getUserAgent((JavascriptExecutor) getWebDriver()); // } // } // // /** // * @param testMethod the method about to run, used to extract the test name // * @see #beforeTestMethod(String) // */ // public void beforeTestMethod(Method testMethod) { // beforeTestMethod(getTestNameForCapture(testMethod)); // } // // private String getTestNameForCapture(Method testMethod) { // Optional<String> testID = TestIdUtils.getIssueOrTmsLinkValue(testMethod); // if (!testID.isPresent() || testID.get().isEmpty()) { // testID = Optional.of(StringUtils.abbreviate(testMethod.getName(), 20)); // } // return testID.orElse("n/a"); // } // // /** // * Run after each test method to clear or tear down the browser // */ // public void afterTestMethod() { // driverLifecycle.tearDownDriver(); // } // // /** // * Run after the entire test suite to: // * clear down the browser pool, send remaining screenshots to Capture // * and create properties for Allure. // */ // public void afterTestSuite() { // driverLifecycle.tearDownDriverPool(); // ScreenshotCapture.processRemainingBacklog(); // AllureProperties.createUI(); // } // // /** // * @return new Wait with default timeout. // * @deprecated use {@code UITestLifecycle.get().getWait()} instead. // */ // @Deprecated // public Wait<WebDriver> newDefaultWait() { // return newWaitWithTimeout(DEFAULT_TIMEOUT); // } // // /** // * @param timeout timeout for the new Wait // * @return a Wait with the given timeout // */ // public Wait<WebDriver> newWaitWithTimeout(Duration timeout) { // return new FluentWait<>(getWebDriver()) // .withTimeout(timeout) // .ignoring(NoSuchElementException.class) // .ignoring(StaleElementReferenceException.class); // } // // public WebDriver getWebDriver() { // return driverLifecycle.getWebDriver(); // } // // public ScreenshotCapture getCapture() { // return capture.get(); // } // // public Wait<WebDriver> getWait() { // return wait.get(); // } // // /** // * @return the user agent of the browser in the first UI test to run. // */ // public Optional<String> getUserAgent() { // return Optional.ofNullable(userAgent); // } // // /** // * @return the session ID of the remote WebDriver // */ // public String getRemoteSessionId() { // return Objects.toString(((RemoteWebDriver) getWebDriver()).getSessionId()); // } // } // Path: src/main/java/com/frameworkium/core/ui/capture/model/Browser.java import static com.frameworkium.core.common.properties.Property.BROWSER; import static com.frameworkium.core.common.properties.Property.BROWSER_VERSION; import static com.frameworkium.core.common.properties.Property.DEVICE; import static com.frameworkium.core.common.properties.Property.PLATFORM; import static com.frameworkium.core.common.properties.Property.PLATFORM_VERSION; import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.UITestLifecycle; import com.frameworkium.core.ui.driver.DriverSetup; import java.util.Optional; import net.sf.uadetector.ReadableUserAgent; import net.sf.uadetector.UserAgentStringParser; import net.sf.uadetector.service.UADetectorServiceFactory; package com.frameworkium.core.ui.capture.model; @JsonInclude(JsonInclude.Include.NON_NULL) public class Browser { public String name; public String version; public String device; public String platform; public String platformVersion; /** * Create browser object. */ public Browser() {
Optional<String> userAgent = UITestLifecycle.get().getUserAgent();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/restfulbooker/api/dto/booking/search/SearchParamsMapper.java
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/dto/booking/Booking.java // public class Booking extends AbstractDTO<Booking> { // public String firstname; // public String lastname; // public long totalprice; // public boolean depositpaid; // public BookingDates bookingdates; // public String additionalneeds; // // public static Booking newInstance() { // ThreadLocalRandom random = ThreadLocalRandom.current(); // int randInt = random.nextInt(); // Booking booking = new Booking(); // booking.firstname = "firstname" + randInt; // booking.lastname = "lastname" + randInt; // booking.totalprice = randInt; // booking.depositpaid = random.nextBoolean(); // booking.bookingdates = BookingDates.newInstance(); // booking.additionalneeds = null; // return booking; // } // }
import com.frameworkium.integration.restfulbooker.api.dto.booking.Booking; import com.google.common.collect.ImmutableMap; import java.util.Map;
package com.frameworkium.integration.restfulbooker.api.dto.booking.search; public class SearchParamsMapper { private SearchParamsMapper() { // hide constructor of mapper }
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/dto/booking/Booking.java // public class Booking extends AbstractDTO<Booking> { // public String firstname; // public String lastname; // public long totalprice; // public boolean depositpaid; // public BookingDates bookingdates; // public String additionalneeds; // // public static Booking newInstance() { // ThreadLocalRandom random = ThreadLocalRandom.current(); // int randInt = random.nextInt(); // Booking booking = new Booking(); // booking.firstname = "firstname" + randInt; // booking.lastname = "lastname" + randInt; // booking.totalprice = randInt; // booking.depositpaid = random.nextBoolean(); // booking.bookingdates = BookingDates.newInstance(); // booking.additionalneeds = null; // return booking; // } // } // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/dto/booking/search/SearchParamsMapper.java import com.frameworkium.integration.restfulbooker.api.dto.booking.Booking; import com.google.common.collect.ImmutableMap; import java.util.Map; package com.frameworkium.integration.restfulbooker.api.dto.booking.search; public class SearchParamsMapper { private SearchParamsMapper() { // hide constructor of mapper }
public static Map<String, String> namesOfBooking(Booking booking) {
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/seleniumhq/tests/SeleniumTest.java
// Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java // public class HomePage extends BasePage<HomePage> { // // @CacheLookup // @Visible // private HeaderComponent header; // // @FindBy(css = "button[data-target='#main_navbar']") // private WebElement menuLink; // // public static HomePage open() { // return PageFactory.newInstance( // HomePage.class, // "https://selenium.dev/"); // } // // public HeaderComponent getHeader() { // // when using Selenium grid, the browser size is smaller and the header is hidden behind this link // if (menuLink.isDisplayed()) { // menuLink.click(); // } // return header; // } // }
import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.seleniumhq.pages.HomePage; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.seleniumhq.tests; public class SeleniumTest extends BaseUITest { public final void component_example_test() {
// Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java // public class HomePage extends BasePage<HomePage> { // // @CacheLookup // @Visible // private HeaderComponent header; // // @FindBy(css = "button[data-target='#main_navbar']") // private WebElement menuLink; // // public static HomePage open() { // return PageFactory.newInstance( // HomePage.class, // "https://selenium.dev/"); // } // // public HeaderComponent getHeader() { // // when using Selenium grid, the browser size is smaller and the header is hidden behind this link // if (menuLink.isDisplayed()) { // menuLink.click(); // } // return header; // } // } // Path: src/test/java/com/frameworkium/integration/seleniumhq/tests/SeleniumTest.java import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.seleniumhq.pages.HomePage; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.seleniumhq.tests; public class SeleniumTest extends BaseUITest { public final void component_example_test() {
String latestVersion = HomePage.open()
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/constant/BookerEndpoint.java // public enum BookerEndpoint implements Endpoint { // // BASE_URI("https://restful-booker.herokuapp.com"), // PING("/ping"), // BOOKING("/booking"), // BOOKING_ID("/booking/%d"), // AUTH("/auth"); // // private String url; // // BookerEndpoint(String url) { // this.url = url; // } // // /** // * @param params Arguments referenced by the format specifiers in the url. // * @return A formatted String representing the URL of the given constant. // */ // @Override // public String getUrl(Object... params) { // return String.format(url, params); // } // // }
import com.frameworkium.integration.restfulbooker.api.constant.BookerEndpoint; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.AbstractBookerService; import com.google.common.collect.ImmutableMap; import io.restassured.http.Method; import java.util.List; import java.util.Map;
package com.frameworkium.integration.restfulbooker.api.service.booking; public class BookingService extends AbstractBookerService { public List<BookingID> listBookings() {
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/constant/BookerEndpoint.java // public enum BookerEndpoint implements Endpoint { // // BASE_URI("https://restful-booker.herokuapp.com"), // PING("/ping"), // BOOKING("/booking"), // BOOKING_ID("/booking/%d"), // AUTH("/auth"); // // private String url; // // BookerEndpoint(String url) { // this.url = url; // } // // /** // * @param params Arguments referenced by the format specifiers in the url. // * @return A formatted String representing the URL of the given constant. // */ // @Override // public String getUrl(Object... params) { // return String.format(url, params); // } // // } // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java import com.frameworkium.integration.restfulbooker.api.constant.BookerEndpoint; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.AbstractBookerService; import com.google.common.collect.ImmutableMap; import io.restassured.http.Method; import java.util.List; import java.util.Map; package com.frameworkium.integration.restfulbooker.api.service.booking; public class BookingService extends AbstractBookerService { public List<BookingID> listBookings() {
return get(BookerEndpoint.BOOKING.getUrl())
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/common/reporting/jira/zapi/Cycle.java
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateCycleSuccessDto.java // public class CreateCycleSuccessDto extends AbstractDTO<CreateCycleSuccessDto> { // public String id; // public String responseMessage; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateNewCycleDto.java // @JsonDeserialize(builder = CreateNewCycleDto.Builder.class) // public class CreateNewCycleDto extends AbstractDTO<CreateNewCycleDto> { // @JsonUnwrapped // public CycleLightDto cycleLightDto; // public String cloneCycleId; // public String sprintId; // // private CreateNewCycleDto(final Builder builder) { // cycleLightDto = builder.cycleLightDto; // cloneCycleId = builder.cloneCycleId; // sprintId = builder.sprintId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // @JsonUnwrapped // private CycleLightDto cycleLightDto; // private String cloneCycleId; // private String sprintId; // // private Builder() { // } // // public Builder cycleLightDto(final CycleLightDto cycleLightDto) { // this.cycleLightDto = cycleLightDto; // return this; // } // // public Builder cloneCycleId(final String cloneCycleId) { // this.cloneCycleId = cloneCycleId; // return this; // } // // public Builder sprintId(final String sprintId) { // this.sprintId = sprintId; // return this; // } // // public CreateNewCycleDto build() { // return new CreateNewCycleDto(this); // } // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CycleListDto.java // public class CycleListDto extends AbstractDTO<CycleListDto> { // public Map<String, CycleDto> map = new HashMap<>(); // public Long recordsCount; // // @JsonCreator // public CycleListDto(@JsonProperty("recordsCount") Long recordsCount) { // this.recordsCount = recordsCount; // } // // @JsonAnySetter // public void setMap(String key, CycleDto cycleDto) { // map.put(key, cycleDto); // } // // @JsonAnyGetter // public Map<String, CycleDto> getMap() { // return map; // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/service/AbstractJiraService.java // public abstract class AbstractJiraService extends BaseService { // @Override // protected RequestSpecification getRequestSpec() { // return RestAssured.given().log().ifValidationFails() // .baseUri(JiraEndpoint.BASE_URI.getUrl()) // .config(config()) // .relaxedHTTPSValidation() // .auth().preemptive().basic( // Property.JIRA_USERNAME.getValue(), // Property.JIRA_PASSWORD.getValue()); // } // // @Override // protected ResponseSpecification getResponseSpec() { // throw new UnsupportedOperationException("Unimplemented"); // } // // private RestAssuredConfig config() { // return RestAssuredConfig.config().objectMapperConfig( // ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory( // (type, s) -> { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.registerModule(new JavaTimeModule()); // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // return objectMapper; // } // ) // ); // } // }
import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateCycleSuccessDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateNewCycleDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CycleListDto; import com.frameworkium.core.common.reporting.jira.endpoint.ZephyrEndpoint; import com.frameworkium.core.common.reporting.jira.service.AbstractJiraService;
package com.frameworkium.core.common.reporting.jira.zapi; public class Cycle extends AbstractJiraService { public CycleListDto getListOfCycle(Long projectId, Long versionId) { return getRequestSpec() .basePath(ZephyrEndpoint.CYCLE.getUrl()) .queryParam("projectId", projectId) .queryParam("versionId", versionId) .get() .then() .log().ifValidationFails() .statusCode(SC_OK) .extract().body() .as(CycleListDto.class); }
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateCycleSuccessDto.java // public class CreateCycleSuccessDto extends AbstractDTO<CreateCycleSuccessDto> { // public String id; // public String responseMessage; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateNewCycleDto.java // @JsonDeserialize(builder = CreateNewCycleDto.Builder.class) // public class CreateNewCycleDto extends AbstractDTO<CreateNewCycleDto> { // @JsonUnwrapped // public CycleLightDto cycleLightDto; // public String cloneCycleId; // public String sprintId; // // private CreateNewCycleDto(final Builder builder) { // cycleLightDto = builder.cycleLightDto; // cloneCycleId = builder.cloneCycleId; // sprintId = builder.sprintId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // @JsonUnwrapped // private CycleLightDto cycleLightDto; // private String cloneCycleId; // private String sprintId; // // private Builder() { // } // // public Builder cycleLightDto(final CycleLightDto cycleLightDto) { // this.cycleLightDto = cycleLightDto; // return this; // } // // public Builder cloneCycleId(final String cloneCycleId) { // this.cloneCycleId = cloneCycleId; // return this; // } // // public Builder sprintId(final String sprintId) { // this.sprintId = sprintId; // return this; // } // // public CreateNewCycleDto build() { // return new CreateNewCycleDto(this); // } // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CycleListDto.java // public class CycleListDto extends AbstractDTO<CycleListDto> { // public Map<String, CycleDto> map = new HashMap<>(); // public Long recordsCount; // // @JsonCreator // public CycleListDto(@JsonProperty("recordsCount") Long recordsCount) { // this.recordsCount = recordsCount; // } // // @JsonAnySetter // public void setMap(String key, CycleDto cycleDto) { // map.put(key, cycleDto); // } // // @JsonAnyGetter // public Map<String, CycleDto> getMap() { // return map; // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/service/AbstractJiraService.java // public abstract class AbstractJiraService extends BaseService { // @Override // protected RequestSpecification getRequestSpec() { // return RestAssured.given().log().ifValidationFails() // .baseUri(JiraEndpoint.BASE_URI.getUrl()) // .config(config()) // .relaxedHTTPSValidation() // .auth().preemptive().basic( // Property.JIRA_USERNAME.getValue(), // Property.JIRA_PASSWORD.getValue()); // } // // @Override // protected ResponseSpecification getResponseSpec() { // throw new UnsupportedOperationException("Unimplemented"); // } // // private RestAssuredConfig config() { // return RestAssuredConfig.config().objectMapperConfig( // ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory( // (type, s) -> { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.registerModule(new JavaTimeModule()); // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // return objectMapper; // } // ) // ); // } // } // Path: src/main/java/com/frameworkium/core/common/reporting/jira/zapi/Cycle.java import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateCycleSuccessDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateNewCycleDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CycleListDto; import com.frameworkium.core.common.reporting.jira.endpoint.ZephyrEndpoint; import com.frameworkium.core.common.reporting.jira.service.AbstractJiraService; package com.frameworkium.core.common.reporting.jira.zapi; public class Cycle extends AbstractJiraService { public CycleListDto getListOfCycle(Long projectId, Long versionId) { return getRequestSpec() .basePath(ZephyrEndpoint.CYCLE.getUrl()) .queryParam("projectId", projectId) .queryParam("versionId", versionId) .get() .then() .log().ifValidationFails() .statusCode(SC_OK) .extract().body() .as(CycleListDto.class); }
public CreateCycleSuccessDto createNewCycle(CreateNewCycleDto createNewCycleDto) {
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/common/reporting/jira/zapi/Cycle.java
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateCycleSuccessDto.java // public class CreateCycleSuccessDto extends AbstractDTO<CreateCycleSuccessDto> { // public String id; // public String responseMessage; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateNewCycleDto.java // @JsonDeserialize(builder = CreateNewCycleDto.Builder.class) // public class CreateNewCycleDto extends AbstractDTO<CreateNewCycleDto> { // @JsonUnwrapped // public CycleLightDto cycleLightDto; // public String cloneCycleId; // public String sprintId; // // private CreateNewCycleDto(final Builder builder) { // cycleLightDto = builder.cycleLightDto; // cloneCycleId = builder.cloneCycleId; // sprintId = builder.sprintId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // @JsonUnwrapped // private CycleLightDto cycleLightDto; // private String cloneCycleId; // private String sprintId; // // private Builder() { // } // // public Builder cycleLightDto(final CycleLightDto cycleLightDto) { // this.cycleLightDto = cycleLightDto; // return this; // } // // public Builder cloneCycleId(final String cloneCycleId) { // this.cloneCycleId = cloneCycleId; // return this; // } // // public Builder sprintId(final String sprintId) { // this.sprintId = sprintId; // return this; // } // // public CreateNewCycleDto build() { // return new CreateNewCycleDto(this); // } // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CycleListDto.java // public class CycleListDto extends AbstractDTO<CycleListDto> { // public Map<String, CycleDto> map = new HashMap<>(); // public Long recordsCount; // // @JsonCreator // public CycleListDto(@JsonProperty("recordsCount") Long recordsCount) { // this.recordsCount = recordsCount; // } // // @JsonAnySetter // public void setMap(String key, CycleDto cycleDto) { // map.put(key, cycleDto); // } // // @JsonAnyGetter // public Map<String, CycleDto> getMap() { // return map; // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/service/AbstractJiraService.java // public abstract class AbstractJiraService extends BaseService { // @Override // protected RequestSpecification getRequestSpec() { // return RestAssured.given().log().ifValidationFails() // .baseUri(JiraEndpoint.BASE_URI.getUrl()) // .config(config()) // .relaxedHTTPSValidation() // .auth().preemptive().basic( // Property.JIRA_USERNAME.getValue(), // Property.JIRA_PASSWORD.getValue()); // } // // @Override // protected ResponseSpecification getResponseSpec() { // throw new UnsupportedOperationException("Unimplemented"); // } // // private RestAssuredConfig config() { // return RestAssuredConfig.config().objectMapperConfig( // ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory( // (type, s) -> { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.registerModule(new JavaTimeModule()); // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // return objectMapper; // } // ) // ); // } // }
import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateCycleSuccessDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateNewCycleDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CycleListDto; import com.frameworkium.core.common.reporting.jira.endpoint.ZephyrEndpoint; import com.frameworkium.core.common.reporting.jira.service.AbstractJiraService;
package com.frameworkium.core.common.reporting.jira.zapi; public class Cycle extends AbstractJiraService { public CycleListDto getListOfCycle(Long projectId, Long versionId) { return getRequestSpec() .basePath(ZephyrEndpoint.CYCLE.getUrl()) .queryParam("projectId", projectId) .queryParam("versionId", versionId) .get() .then() .log().ifValidationFails() .statusCode(SC_OK) .extract().body() .as(CycleListDto.class); }
// Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateCycleSuccessDto.java // public class CreateCycleSuccessDto extends AbstractDTO<CreateCycleSuccessDto> { // public String id; // public String responseMessage; // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CreateNewCycleDto.java // @JsonDeserialize(builder = CreateNewCycleDto.Builder.class) // public class CreateNewCycleDto extends AbstractDTO<CreateNewCycleDto> { // @JsonUnwrapped // public CycleLightDto cycleLightDto; // public String cloneCycleId; // public String sprintId; // // private CreateNewCycleDto(final Builder builder) { // cycleLightDto = builder.cycleLightDto; // cloneCycleId = builder.cloneCycleId; // sprintId = builder.sprintId; // } // // public static Builder newBuilder() { // return new Builder(); // } // // @JsonPOJOBuilder(withPrefix = "") // public static final class Builder { // @JsonUnwrapped // private CycleLightDto cycleLightDto; // private String cloneCycleId; // private String sprintId; // // private Builder() { // } // // public Builder cycleLightDto(final CycleLightDto cycleLightDto) { // this.cycleLightDto = cycleLightDto; // return this; // } // // public Builder cloneCycleId(final String cloneCycleId) { // this.cloneCycleId = cloneCycleId; // return this; // } // // public Builder sprintId(final String sprintId) { // this.sprintId = sprintId; // return this; // } // // public CreateNewCycleDto build() { // return new CreateNewCycleDto(this); // } // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/dto/cycle/CycleListDto.java // public class CycleListDto extends AbstractDTO<CycleListDto> { // public Map<String, CycleDto> map = new HashMap<>(); // public Long recordsCount; // // @JsonCreator // public CycleListDto(@JsonProperty("recordsCount") Long recordsCount) { // this.recordsCount = recordsCount; // } // // @JsonAnySetter // public void setMap(String key, CycleDto cycleDto) { // map.put(key, cycleDto); // } // // @JsonAnyGetter // public Map<String, CycleDto> getMap() { // return map; // } // } // // Path: src/main/java/com/frameworkium/core/common/reporting/jira/service/AbstractJiraService.java // public abstract class AbstractJiraService extends BaseService { // @Override // protected RequestSpecification getRequestSpec() { // return RestAssured.given().log().ifValidationFails() // .baseUri(JiraEndpoint.BASE_URI.getUrl()) // .config(config()) // .relaxedHTTPSValidation() // .auth().preemptive().basic( // Property.JIRA_USERNAME.getValue(), // Property.JIRA_PASSWORD.getValue()); // } // // @Override // protected ResponseSpecification getResponseSpec() { // throw new UnsupportedOperationException("Unimplemented"); // } // // private RestAssuredConfig config() { // return RestAssuredConfig.config().objectMapperConfig( // ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory( // (type, s) -> { // final ObjectMapper objectMapper = new ObjectMapper(); // objectMapper.registerModule(new JavaTimeModule()); // objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // objectMapper.setVisibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE); // objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); // objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); // return objectMapper; // } // ) // ); // } // } // Path: src/main/java/com/frameworkium/core/common/reporting/jira/zapi/Cycle.java import static org.apache.http.HttpStatus.SC_OK; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateCycleSuccessDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CreateNewCycleDto; import com.frameworkium.core.common.reporting.jira.dto.cycle.CycleListDto; import com.frameworkium.core.common.reporting.jira.endpoint.ZephyrEndpoint; import com.frameworkium.core.common.reporting.jira.service.AbstractJiraService; package com.frameworkium.core.common.reporting.jira.zapi; public class Cycle extends AbstractJiraService { public CycleListDto getListOfCycle(Long projectId, Long versionId) { return getRequestSpec() .basePath(ZephyrEndpoint.CYCLE.getUrl()) .queryParam("projectId", projectId) .queryParam("versionId", versionId) .get() .then() .log().ifValidationFails() .statusCode(SC_OK) .extract().body() .as(CycleListDto.class); }
public CreateCycleSuccessDto createNewCycle(CreateNewCycleDto createNewCycleDto) {
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/DragAndDropPage.java
// Path: src/main/java/com/frameworkium/core/common/reporting/allure/AllureLogger.java // public class AllureLogger { // // private static final Logger logger = LogManager.getLogger(); // private static final ThreadLocal<Deque<String>> STEP_UUID_STACK = // ThreadLocal.withInitial(ArrayDeque::new); // // private AllureLogger() { // // hide default constructor for this util class // } // // /** // * Uses the @Step annotation to log the given log message to Allure. // * // * @param message the message to log to the allure report // */ // @Step("{message}") // public static void logToAllure(String message) { // logger.debug("Logged to allure: " + message); // } // // public static void stepStart(String stepName) { // StepResult result = new StepResult().setName(stepName); // String uuid = UUID.randomUUID().toString(); // getLifecycle().startStep(uuid, result); // STEP_UUID_STACK.get().addFirst(uuid); // } // // public static void stepFinish() { // getLifecycle().stopStep(STEP_UUID_STACK.get().removeFirst()); // } // }
import com.frameworkium.core.common.reporting.allure.AllureLogger; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import io.qameta.allure.Step; import io.restassured.RestAssured; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.stream.Collectors;
"dispatchEvent(a,n,s)},createEvent:function(t){var a=document." + "createEvent(\"CustomEvent\");return a.initCustomEvent(t,!0,!0,null)," + "a.dataTransfer={data:{},setData:function(t,a){this.data[t]=a}," + "getData:function(t){return this.data[t]}},a},dispatchEvent:" + "function(t,a,e){t.dispatchEvent?t.dispatchEvent(e):t.fireEvent&&t.fireEvent(\"on\"+a,e)}})}(jQuery);"; /** * Fetches Javascript from the Internet used to be able to simulate Drag and Drop. * * @return a String containing the Javascript for JQuery (if not already present on the page) * and code for simulating drag and drop. */ private String scriptToSimulateDragDrop() { if (jQueryJS.isEmpty()) { Boolean isJQueryAvailable = (Boolean) executeJS("return !!window.jQuery;"); if (!isJQueryAvailable) { jQueryJS = RestAssured.get(JQUERY_JS_URI).asString(); } } return jQueryJS + dragDropHelperJS; } /** * @param from the jQuery selector for the element to initially click and then drag * @param to the jQuery selector for the target element where the from element will be dropped */ private void simulateDragAndDrop(String from, String to) { executeJS(scriptToSimulateDragDrop()); // TODO: move AllureLogger steps to dedicated test
// Path: src/main/java/com/frameworkium/core/common/reporting/allure/AllureLogger.java // public class AllureLogger { // // private static final Logger logger = LogManager.getLogger(); // private static final ThreadLocal<Deque<String>> STEP_UUID_STACK = // ThreadLocal.withInitial(ArrayDeque::new); // // private AllureLogger() { // // hide default constructor for this util class // } // // /** // * Uses the @Step annotation to log the given log message to Allure. // * // * @param message the message to log to the allure report // */ // @Step("{message}") // public static void logToAllure(String message) { // logger.debug("Logged to allure: " + message); // } // // public static void stepStart(String stepName) { // StepResult result = new StepResult().setName(stepName); // String uuid = UUID.randomUUID().toString(); // getLifecycle().startStep(uuid, result); // STEP_UUID_STACK.get().addFirst(uuid); // } // // public static void stepFinish() { // getLifecycle().stopStep(STEP_UUID_STACK.get().removeFirst()); // } // } // Path: src/test/java/com/frameworkium/integration/theinternet/pages/DragAndDropPage.java import com.frameworkium.core.common.reporting.allure.AllureLogger; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import io.qameta.allure.Step; import io.restassured.RestAssured; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.stream.Collectors; "dispatchEvent(a,n,s)},createEvent:function(t){var a=document." + "createEvent(\"CustomEvent\");return a.initCustomEvent(t,!0,!0,null)," + "a.dataTransfer={data:{},setData:function(t,a){this.data[t]=a}," + "getData:function(t){return this.data[t]}},a},dispatchEvent:" + "function(t,a,e){t.dispatchEvent?t.dispatchEvent(e):t.fireEvent&&t.fireEvent(\"on\"+a,e)}})}(jQuery);"; /** * Fetches Javascript from the Internet used to be able to simulate Drag and Drop. * * @return a String containing the Javascript for JQuery (if not already present on the page) * and code for simulating drag and drop. */ private String scriptToSimulateDragDrop() { if (jQueryJS.isEmpty()) { Boolean isJQueryAvailable = (Boolean) executeJS("return !!window.jQuery;"); if (!isJQueryAvailable) { jQueryJS = RestAssured.get(JQUERY_JS_URI).asString(); } } return jQueryJS + dragDropHelperJS; } /** * @param from the jQuery selector for the element to initially click and then drag * @param to the jQuery selector for the target element where the from element will be dropped */ private void simulateDragAndDrop(String from, String to) { executeJS(scriptToSimulateDragDrop()); // TODO: move AllureLogger steps to dedicated test
AllureLogger.stepStart("testing step start");
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/DynamicLoadingExamplePage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.htmlelements.annotations.Timeout; import com.frameworkium.core.htmlelements.element.Button; import com.frameworkium.core.htmlelements.element.HtmlElement; import com.frameworkium.core.ui.annotations.Invisible; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import io.qameta.allure.Step; import org.openqa.selenium.support.FindBy; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;
package com.frameworkium.integration.theinternet.pages; public class DynamicLoadingExamplePage extends BasePage<DynamicLoadingExamplePage> { @Visible @FindBy(css = "#start button") private Button startButton; @Invisible @Timeout(0) // prevents page load taking 5s due to implicit timeout @FindBy(id = "finish") private HtmlElement dynamicElement; public static DynamicLoadingExamplePage openExampleTwo() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/theinternet/pages/DynamicLoadingExamplePage.java import com.frameworkium.core.htmlelements.annotations.Timeout; import com.frameworkium.core.htmlelements.element.Button; import com.frameworkium.core.htmlelements.element.HtmlElement; import com.frameworkium.core.ui.annotations.Invisible; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import io.qameta.allure.Step; import org.openqa.selenium.support.FindBy; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; package com.frameworkium.integration.theinternet.pages; public class DynamicLoadingExamplePage extends BasePage<DynamicLoadingExamplePage> { @Visible @FindBy(css = "#start button") private Button startButton; @Invisible @Timeout(0) // prevents page load taking 5s due to implicit timeout @FindBy(id = "finish") private HtmlElement dynamicElement; public static DynamicLoadingExamplePage openExampleTwo() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/driver/drivers/SauceImpl.java
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/Sauce.java // public class Sauce { // // private static final SauceOnDemandAuthentication sauceAuth = // new SauceOnDemandAuthentication( // System.getenv("SAUCE_USERNAME"), // System.getenv("SAUCE_ACCESS_KEY")); // // private static final SauceREST client = // new SauceREST( // sauceAuth.getUsername(), // sauceAuth.getAccessKey()); // // public static URL getURL() { // try { // return new URL(String.format( // "https://%s:%[email protected]/wd/hub", // sauceAuth.getUsername(), // sauceAuth.getAccessKey())); // } catch (MalformedURLException e) { // throw new IllegalArgumentException(e); // } // } // // public static boolean isDesired() { // return Property.SAUCE.getBoolean(); // } // // public static void updateJobName(SauceOnDemandSessionIdProvider sessionIdProvider, String name) { // // client.updateJobInfo( // sessionIdProvider.getSessionId(), // ImmutableMap.of("name", name)); // } // // public static void uploadFile(File file) throws IOException { // client.uploadFile(file); // } // // }
import static com.frameworkium.core.common.properties.Property.APP_PATH; import static com.frameworkium.core.common.properties.Property.BROWSER_VERSION; import static com.frameworkium.core.common.properties.Property.BUILD; import static com.frameworkium.core.common.properties.Property.DEVICE; import static com.frameworkium.core.common.properties.Property.PLATFORM_VERSION; import static com.frameworkium.core.ui.driver.DriverSetup.Platform; import com.frameworkium.core.ui.driver.AbstractDriver; import com.frameworkium.core.ui.driver.Driver; import com.frameworkium.core.ui.driver.remotes.Sauce; import java.io.File; import java.net.URL; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.RemoteWebDriver;
package com.frameworkium.core.ui.driver.drivers; public class SauceImpl extends AbstractDriver { private Platform platform; private Capabilities capabilities; private URL remoteURL; public SauceImpl(Platform platform, Capabilities capabilities) { this.platform = platform; this.capabilities = capabilities;
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/Sauce.java // public class Sauce { // // private static final SauceOnDemandAuthentication sauceAuth = // new SauceOnDemandAuthentication( // System.getenv("SAUCE_USERNAME"), // System.getenv("SAUCE_ACCESS_KEY")); // // private static final SauceREST client = // new SauceREST( // sauceAuth.getUsername(), // sauceAuth.getAccessKey()); // // public static URL getURL() { // try { // return new URL(String.format( // "https://%s:%[email protected]/wd/hub", // sauceAuth.getUsername(), // sauceAuth.getAccessKey())); // } catch (MalformedURLException e) { // throw new IllegalArgumentException(e); // } // } // // public static boolean isDesired() { // return Property.SAUCE.getBoolean(); // } // // public static void updateJobName(SauceOnDemandSessionIdProvider sessionIdProvider, String name) { // // client.updateJobInfo( // sessionIdProvider.getSessionId(), // ImmutableMap.of("name", name)); // } // // public static void uploadFile(File file) throws IOException { // client.uploadFile(file); // } // // } // Path: src/main/java/com/frameworkium/core/ui/driver/drivers/SauceImpl.java import static com.frameworkium.core.common.properties.Property.APP_PATH; import static com.frameworkium.core.common.properties.Property.BROWSER_VERSION; import static com.frameworkium.core.common.properties.Property.BUILD; import static com.frameworkium.core.common.properties.Property.DEVICE; import static com.frameworkium.core.common.properties.Property.PLATFORM_VERSION; import static com.frameworkium.core.ui.driver.DriverSetup.Platform; import com.frameworkium.core.ui.driver.AbstractDriver; import com.frameworkium.core.ui.driver.Driver; import com.frameworkium.core.ui.driver.remotes.Sauce; import java.io.File; import java.net.URL; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.RemoteWebDriver; package com.frameworkium.core.ui.driver.drivers; public class SauceImpl extends AbstractDriver { private Platform platform; private Capabilities capabilities; private URL remoteURL; public SauceImpl(Platform platform, Capabilities capabilities) { this.platform = platform; this.capabilities = capabilities;
this.remoteURL = Sauce.getURL();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.capture.api.tests; /** Tests for the Capture execution API. */ @Ignore public class CaptureExecutionAPITest extends BaseAPITest { private CreateExecution createExMessage; private String executionID; /** * Using {@link BeforeClass} to ensure anything like: * https://github.com/cbeust/testng/issues/1660 * gets caught before we release. * This, with threads, is a common pattern. */ @BeforeClass public void create_execution() { createExMessage = CreateExecution.newCreateInstance();
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // } // Path: src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.capture.api.tests; /** Tests for the Capture execution API. */ @Ignore public class CaptureExecutionAPITest extends BaseAPITest { private CreateExecution createExMessage; private String executionID; /** * Using {@link BeforeClass} to ensure anything like: * https://github.com/cbeust/testng/issues/1660 * gets caught before we release. * This, with threads, is a common pattern. */ @BeforeClass public void create_execution() { createExMessage = CreateExecution.newCreateInstance();
executionID = new ExecutionService()
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat;
List<ExecutionResponse> filteredExecutions = latestExecutions .results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() {
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // } // Path: src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat; List<ExecutionResponse> filteredExecutions = latestExecutions .results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() {
CreateScreenshot createScreenshot = CreateScreenshot.newInstance(executionID);
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat;
List<ExecutionResponse> filteredExecutions = latestExecutions .results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() { CreateScreenshot createScreenshot = CreateScreenshot.newInstance(executionID);
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // } // Path: src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat; List<ExecutionResponse> filteredExecutions = latestExecutions .results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() { CreateScreenshot createScreenshot = CreateScreenshot.newInstance(executionID);
new ScreenshotService().createScreenshot(createScreenshot);
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat;
.results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() { CreateScreenshot createScreenshot = CreateScreenshot.newInstance(executionID); new ScreenshotService().createScreenshot(createScreenshot);
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/CreateScreenshot.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class CreateScreenshot extends AbstractDTO<CreateScreenshot> { // // public Command command; // public String url; // public String executionID; // public String errorMessage; // public String screenshotBase64; // // public static CreateScreenshot newInstance(String executionID) { // CreateScreenshot createScreenshot = new CreateScreenshot(); // createScreenshot.executionID = executionID; // createScreenshot.command = Command.newInstance(); // createScreenshot.url = "http://test.url/hello?x=1&y=2"; // createScreenshot.errorMessage = null; // createScreenshot.screenshotBase64 = getBase64TestImage(); // return createScreenshot; // } // // private static String getBase64TestImage() { // try { // InputStream imageStream = CreateScreenshot.class.getClassLoader() // .getResourceAsStream("capture-screenshot.png"); // byte[] bytes = IOUtils.toByteArray(imageStream); // return Base64.getEncoder().encodeToString(bytes); // } catch (IOException e) { // throw new IllegalStateException(e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/dto/screenshots/Screenshot.java // public class Screenshot extends AbstractDTO<Screenshot> { // // public Command command; // public String imageURL; // public String timestamp; // public String url; // // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/executions/ExecutionService.java // public class ExecutionService extends BaseCaptureService { // // @Step("Create Capture Execution {createMessage}") // public ExecutionID createExecution(CreateExecution createMessage) { // return post(CaptureEndpoint.EXECUTIONS.getUrl(), createMessage) // .extract() // .as(ExecutionID.class); // } // // @Step("Get Capture Executions, page={page}, pageSize={pageSize}") // public ExecutionResults getExecutions(int page, int pageSize) { // return get( // ImmutableMap.of("page", page, "pageSize", pageSize), // CaptureEndpoint.EXECUTIONS.getUrl()) // .as(ExecutionResults.class); // } // // public ExecutionResponse getExecution(String executionID) { // return get(CaptureEndpoint.GET_EXECUTION.getUrl(executionID)) // .as(ExecutionResponse.class); // } // } // // Path: src/test/java/com/frameworkium/integration/capture/api/service/screenshots/ScreenshotService.java // public class ScreenshotService extends BaseCaptureService { // // public void createScreenshot(CreateScreenshot createMessage) { // post(CaptureEndpoint.SCREENSHOT.getUrl(), createMessage); // } // // } // Path: src/test/java/com/frameworkium/integration/capture/api/tests/CaptureExecutionAPITest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.integration.capture.api.dto.executions.*; import com.frameworkium.integration.capture.api.dto.screenshots.CreateScreenshot; import com.frameworkium.integration.capture.api.dto.screenshots.Screenshot; import com.frameworkium.integration.capture.api.service.executions.ExecutionService; import com.frameworkium.integration.capture.api.service.screenshots.ScreenshotService; import org.openqa.selenium.NotFoundException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Ignore; import org.testng.annotations.Test; import java.util.List; import java.util.stream.Collectors; import static com.google.common.truth.Truth.assertThat; .results.stream() .filter(ex -> executionID.equals(ex.executionID)) .collect(Collectors.toList()); // ensure only one with our expected ID assertThat(filteredExecutions).hasSize(1); ExecutionResponse response = filteredExecutions.get(0); assertThat(response.createdFrom(createExMessage)).isTrue(); } @Test public void new_execution_has_status_new_and_last_updated_equals_created() { String id = new ExecutionService() .createExecution(createExMessage) .executionID; ExecutionResponse execution = new ExecutionService() .getExecutions(1, 20) .results.stream() .filter(ex -> id.equals(ex.executionID)) .findFirst().orElseThrow(NotFoundException::new); assertThat(execution.currentStatus).isEqualTo("new"); assertThat(execution.lastUpdated).isEqualTo(execution.created); } @Test public void can_add_then_view_screenshot() { CreateScreenshot createScreenshot = CreateScreenshot.newInstance(executionID); new ScreenshotService().createScreenshot(createScreenshot);
Screenshot returnedScreenshot =
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/restfulbooker/api/tests/BookerTest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/main/java/com/frameworkium/core/common/retry/RetryFlakyTest.java // public class RetryFlakyTest implements IRetryAnalyzer { // // /** // * Maximum retry count of failed tests, defaults to 1. // */ // static final int MAX_RETRY_COUNT = // Property.MAX_RETRY_COUNT.getIntWithDefault(1); // // private int retryCount = 0; // // @Override // public boolean retry(ITestResult result) { // return retryCount++ < MAX_RETRY_COUNT; // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java // public class BookingService extends AbstractBookerService { // // public List<BookingID> listBookings() { // return get(BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public Booking getBooking(int id) { // return get(BookerEndpoint.BOOKING_ID.getUrl(id)) // .as(Booking.class); // } // // public CreateBookingResponse createBooking(Booking booking) { // return post(booking, BookerEndpoint.BOOKING.getUrl()) // .as(CreateBookingResponse.class); // } // // public List<BookingID> search(Map<String, String> searchParams) { // return request(Method.GET, searchParams, BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public String createAuthToken(String username, String password) { // return post( // ImmutableMap.of("username", username, "password", password), // BookerEndpoint.AUTH.getUrl()) // .jsonPath().get("token"); // } // // public void delete(int bookingID, String token) { // getRequestSpec() // .cookie("token", token) // .delete(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // // API does not match documentation // // .then() // // .statusCode(HttpStatus.SC_NO_CONTENT) // ; // } // // public boolean doesBookingExist(int bookingID) { // final int statusCode = getRequestSpec() // .get(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // .then() // .extract() // .statusCode(); // if (statusCode == 200) { // return true; // } else if (statusCode == 404) { // return false; // } else { // throw new IllegalStateException("Unexpected return code"); // } // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java // public class PingService extends AbstractBookerService { // // public String ping() { // return get(BookerEndpoint.PING.getUrl()) // .body().asString(); // } // // /** // * Used in template method {@link AbstractBookerService#get(String)} // */ // @Override // protected ResponseSpecification getResponseSpec() { // return RestAssured.expect().response() // .statusCode(HttpStatus.SC_CREATED); // } // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.core.common.retry.RetryFlakyTest; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.booking.BookingService; import com.frameworkium.integration.restfulbooker.api.service.ping.PingService; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.restfulbooker.api.tests; // app resets every 10m, so could happen in the middle of this test @Test(retryAnalyzer = RetryFlakyTest.class) public class BookerTest extends BaseAPITest { @BeforeClass public void ensure_site_is_up_by_using_ping_service() {
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/main/java/com/frameworkium/core/common/retry/RetryFlakyTest.java // public class RetryFlakyTest implements IRetryAnalyzer { // // /** // * Maximum retry count of failed tests, defaults to 1. // */ // static final int MAX_RETRY_COUNT = // Property.MAX_RETRY_COUNT.getIntWithDefault(1); // // private int retryCount = 0; // // @Override // public boolean retry(ITestResult result) { // return retryCount++ < MAX_RETRY_COUNT; // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java // public class BookingService extends AbstractBookerService { // // public List<BookingID> listBookings() { // return get(BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public Booking getBooking(int id) { // return get(BookerEndpoint.BOOKING_ID.getUrl(id)) // .as(Booking.class); // } // // public CreateBookingResponse createBooking(Booking booking) { // return post(booking, BookerEndpoint.BOOKING.getUrl()) // .as(CreateBookingResponse.class); // } // // public List<BookingID> search(Map<String, String> searchParams) { // return request(Method.GET, searchParams, BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public String createAuthToken(String username, String password) { // return post( // ImmutableMap.of("username", username, "password", password), // BookerEndpoint.AUTH.getUrl()) // .jsonPath().get("token"); // } // // public void delete(int bookingID, String token) { // getRequestSpec() // .cookie("token", token) // .delete(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // // API does not match documentation // // .then() // // .statusCode(HttpStatus.SC_NO_CONTENT) // ; // } // // public boolean doesBookingExist(int bookingID) { // final int statusCode = getRequestSpec() // .get(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // .then() // .extract() // .statusCode(); // if (statusCode == 200) { // return true; // } else if (statusCode == 404) { // return false; // } else { // throw new IllegalStateException("Unexpected return code"); // } // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java // public class PingService extends AbstractBookerService { // // public String ping() { // return get(BookerEndpoint.PING.getUrl()) // .body().asString(); // } // // /** // * Used in template method {@link AbstractBookerService#get(String)} // */ // @Override // protected ResponseSpecification getResponseSpec() { // return RestAssured.expect().response() // .statusCode(HttpStatus.SC_CREATED); // } // } // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/tests/BookerTest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.core.common.retry.RetryFlakyTest; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.booking.BookingService; import com.frameworkium.integration.restfulbooker.api.service.ping.PingService; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.restfulbooker.api.tests; // app resets every 10m, so could happen in the middle of this test @Test(retryAnalyzer = RetryFlakyTest.class) public class BookerTest extends BaseAPITest { @BeforeClass public void ensure_site_is_up_by_using_ping_service() {
assertThat(new PingService().ping())
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/restfulbooker/api/tests/BookerTest.java
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/main/java/com/frameworkium/core/common/retry/RetryFlakyTest.java // public class RetryFlakyTest implements IRetryAnalyzer { // // /** // * Maximum retry count of failed tests, defaults to 1. // */ // static final int MAX_RETRY_COUNT = // Property.MAX_RETRY_COUNT.getIntWithDefault(1); // // private int retryCount = 0; // // @Override // public boolean retry(ITestResult result) { // return retryCount++ < MAX_RETRY_COUNT; // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java // public class BookingService extends AbstractBookerService { // // public List<BookingID> listBookings() { // return get(BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public Booking getBooking(int id) { // return get(BookerEndpoint.BOOKING_ID.getUrl(id)) // .as(Booking.class); // } // // public CreateBookingResponse createBooking(Booking booking) { // return post(booking, BookerEndpoint.BOOKING.getUrl()) // .as(CreateBookingResponse.class); // } // // public List<BookingID> search(Map<String, String> searchParams) { // return request(Method.GET, searchParams, BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public String createAuthToken(String username, String password) { // return post( // ImmutableMap.of("username", username, "password", password), // BookerEndpoint.AUTH.getUrl()) // .jsonPath().get("token"); // } // // public void delete(int bookingID, String token) { // getRequestSpec() // .cookie("token", token) // .delete(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // // API does not match documentation // // .then() // // .statusCode(HttpStatus.SC_NO_CONTENT) // ; // } // // public boolean doesBookingExist(int bookingID) { // final int statusCode = getRequestSpec() // .get(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // .then() // .extract() // .statusCode(); // if (statusCode == 200) { // return true; // } else if (statusCode == 404) { // return false; // } else { // throw new IllegalStateException("Unexpected return code"); // } // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java // public class PingService extends AbstractBookerService { // // public String ping() { // return get(BookerEndpoint.PING.getUrl()) // .body().asString(); // } // // /** // * Used in template method {@link AbstractBookerService#get(String)} // */ // @Override // protected ResponseSpecification getResponseSpec() { // return RestAssured.expect().response() // .statusCode(HttpStatus.SC_CREATED); // } // }
import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.core.common.retry.RetryFlakyTest; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.booking.BookingService; import com.frameworkium.integration.restfulbooker.api.service.ping.PingService; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.restfulbooker.api.tests; // app resets every 10m, so could happen in the middle of this test @Test(retryAnalyzer = RetryFlakyTest.class) public class BookerTest extends BaseAPITest { @BeforeClass public void ensure_site_is_up_by_using_ping_service() { assertThat(new PingService().ping()) .isEqualTo("Created"); } public void create_new_booking() { // given some booking data
// Path: src/main/java/com/frameworkium/core/api/tests/BaseAPITest.java // @Listeners({MethodInterceptor.class, // TestListener.class, // ResultLoggerListener.class}) // @Test(groups = "base-api") // public abstract class BaseAPITest { // // protected final Logger logger = LogManager.getLogger(this); // // /** // * Creates the allure properties for the report, after the test run. // */ // @AfterSuite(alwaysRun = true) // public static void createAllureProperties() { // AllureProperties.createAPI(); // } // // } // // Path: src/main/java/com/frameworkium/core/common/retry/RetryFlakyTest.java // public class RetryFlakyTest implements IRetryAnalyzer { // // /** // * Maximum retry count of failed tests, defaults to 1. // */ // static final int MAX_RETRY_COUNT = // Property.MAX_RETRY_COUNT.getIntWithDefault(1); // // private int retryCount = 0; // // @Override // public boolean retry(ITestResult result) { // return retryCount++ < MAX_RETRY_COUNT; // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/booking/BookingService.java // public class BookingService extends AbstractBookerService { // // public List<BookingID> listBookings() { // return get(BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public Booking getBooking(int id) { // return get(BookerEndpoint.BOOKING_ID.getUrl(id)) // .as(Booking.class); // } // // public CreateBookingResponse createBooking(Booking booking) { // return post(booking, BookerEndpoint.BOOKING.getUrl()) // .as(CreateBookingResponse.class); // } // // public List<BookingID> search(Map<String, String> searchParams) { // return request(Method.GET, searchParams, BookerEndpoint.BOOKING.getUrl()) // .jsonPath().getList(".", BookingID.class); // } // // public String createAuthToken(String username, String password) { // return post( // ImmutableMap.of("username", username, "password", password), // BookerEndpoint.AUTH.getUrl()) // .jsonPath().get("token"); // } // // public void delete(int bookingID, String token) { // getRequestSpec() // .cookie("token", token) // .delete(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // // API does not match documentation // // .then() // // .statusCode(HttpStatus.SC_NO_CONTENT) // ; // } // // public boolean doesBookingExist(int bookingID) { // final int statusCode = getRequestSpec() // .get(BookerEndpoint.BOOKING_ID.getUrl(bookingID)) // .then() // .extract() // .statusCode(); // if (statusCode == 200) { // return true; // } else if (statusCode == 404) { // return false; // } else { // throw new IllegalStateException("Unexpected return code"); // } // } // } // // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java // public class PingService extends AbstractBookerService { // // public String ping() { // return get(BookerEndpoint.PING.getUrl()) // .body().asString(); // } // // /** // * Used in template method {@link AbstractBookerService#get(String)} // */ // @Override // protected ResponseSpecification getResponseSpec() { // return RestAssured.expect().response() // .statusCode(HttpStatus.SC_CREATED); // } // } // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/tests/BookerTest.java import com.frameworkium.core.api.tests.BaseAPITest; import com.frameworkium.core.common.retry.RetryFlakyTest; import com.frameworkium.integration.restfulbooker.api.dto.booking.*; import com.frameworkium.integration.restfulbooker.api.service.booking.BookingService; import com.frameworkium.integration.restfulbooker.api.service.ping.PingService; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.restfulbooker.api.tests; // app resets every 10m, so could happen in the middle of this test @Test(retryAnalyzer = RetryFlakyTest.class) public class BookerTest extends BaseAPITest { @BeforeClass public void ensure_site_is_up_by_using_ping_service() { assertThat(new PingService().ping()) .isEqualTo("Created"); } public void create_new_booking() { // given some booking data
BookingService service = new BookingService();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/seleniumhq/pages/SeleniumDownloadPage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // }
import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;
package com.frameworkium.integration.seleniumhq.pages; public class SeleniumDownloadPage extends BasePage<SeleniumDownloadPage> { @Visible
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // } // Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/SeleniumDownloadPage.java import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; package com.frameworkium.integration.seleniumhq.pages; public class SeleniumDownloadPage extends BasePage<SeleniumDownloadPage> { @Visible
private HeaderComponent header;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/seleniumhq/pages/SeleniumDownloadPage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // }
import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf;
package com.frameworkium.integration.seleniumhq.pages; public class SeleniumDownloadPage extends BasePage<SeleniumDownloadPage> { @Visible private HeaderComponent header; @Visible @FindBy(css = "body .td-main div:nth-child(3) > div:nth-child(2) a") private Link latestDownloadLink; public static SeleniumDownloadPage open() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // } // Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/SeleniumDownloadPage.java import com.frameworkium.core.htmlelements.element.Link; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; import static org.openqa.selenium.support.ui.ExpectedConditions.visibilityOf; package com.frameworkium.integration.seleniumhq.pages; public class SeleniumDownloadPage extends BasePage<SeleniumDownloadPage> { @Visible private HeaderComponent header; @Visible @FindBy(css = "body .td-main div:nth-child(3) > div:nth-child(2) a") private Link latestDownloadLink; public static SeleniumDownloadPage open() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/common/listeners/MethodInterceptor.java
// Path: src/main/java/com/frameworkium/core/common/reporting/TestIdUtils.java // public class TestIdUtils { // // private TestIdUtils() { // // hide default constructor for this util class // } // // /** // * Get TMS Link or Issue ID value. // * // * @param iMethod the {@link IMethodInstance} to check for test ID annotations. // * @return Optional of either the {@link TmsLink} or {@link Issue} value. // * @throws IllegalStateException if {@link TmsLink} and {@link Issue} // * are specified inconstantly. // * @deprecated Use // * {@link TestIdUtils#getIssueOrTmsLinkValues(IMethodInstance)} instead // */ // @Deprecated // public static Optional<String> getIssueOrTmsLinkValue(IMethodInstance iMethod) { // Method method = iMethod.getMethod().getConstructorOrMethod().getMethod(); // return getIssueOrTmsLinkValue(method); // } // // /** // * Get {@link TmsLink} or {@link Issue} for a method. // * If both are specified it will return jus the {@link TmsLink} value. // * // * @param method the method to check for test ID annotations. // * @return Optional of the {@link TmsLink} or {@link Issue} value. // * @deprecated Use // * {@link TestIdUtils#getIssueOrTmsLinkValues(Method)} instead. // */ // @Deprecated // public static Optional<String> getIssueOrTmsLinkValue(Method method) { // TmsLink tcIdAnnotation = method.getAnnotation(TmsLink.class); // Issue issueAnnotation = method.getAnnotation(Issue.class); // // if (nonNull(tcIdAnnotation)) { // return Optional.of(tcIdAnnotation.value()); // } else if (nonNull(issueAnnotation)) { // return Optional.of(issueAnnotation.value()); // } else { // return Optional.empty(); // } // } // // /** // * Get list of {@link TmsLink} or {@link Issue}. // * // * @param iMethod the {@link IMethodInstance} to check for test ID annotations. // * @return List of either the {@link TmsLink} or {@link Issue} value. // * @throws IllegalStateException if {@link TmsLink} and {@link Issue} // * are specified inconstantly. // */ // public static List<String> getIssueOrTmsLinkValues(IMethodInstance iMethod) { // Method method = iMethod.getMethod().getConstructorOrMethod().getMethod(); // return getIssueOrTmsLinkValues(method); // } // // /** // * Get a list of {@link TmsLink} or {@link Issue} for a method. // * If both are specified it will return just the list of {@link TmsLink} values. // * // * @param method the method to check for test Id annotations. // * @return List of {@link TmsLink} or {@link Issue} values. // */ // public static List<String> getIssueOrTmsLinkValues(Method method) { // TmsLink[] tcIdAnnotations = method.getAnnotationsByType(TmsLink.class); // Issue[] issueAnnotations = method.getAnnotationsByType(Issue.class); // if (tcIdAnnotations.length > 0) { // return Stream.of(tcIdAnnotations).map(TmsLink::value).collect(Collectors.toList()); // } // if (issueAnnotations.length > 0) { // return Stream.of(issueAnnotations).map(Issue::value).collect(Collectors.toList()); // } // return Collections.emptyList(); // } // }
import static com.frameworkium.core.common.properties.Property.JIRA_URL; import static com.frameworkium.core.common.properties.Property.JQL_QUERY; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import com.frameworkium.core.common.reporting.TestIdUtils; import com.frameworkium.core.common.reporting.jira.service.Search; import java.lang.reflect.Method; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext;
package com.frameworkium.core.common.listeners; public class MethodInterceptor implements IMethodInterceptor { private static final Logger logger = LogManager.getLogger(); @Override public List<IMethodInstance> intercept( List<IMethodInstance> methods, ITestContext context) { return filterTestsToRunByJQL(methods); } private List<IMethodInstance> filterTestsToRunByJQL( List<IMethodInstance> methodsToBeFiltered) { if (!(JQL_QUERY.isSpecified() && JIRA_URL.isSpecified())) { // Can't run the JQL without both JIRA_URL and JQL_QUERY return methodsToBeFiltered; } logger.info("Filtering specified tests to run with JQL query results"); List<String> testIDsFromJQL = new Search(JQL_QUERY.getValue()).getKeys(); List<IMethodInstance> methodsToRun = methodsToBeFiltered.stream()
// Path: src/main/java/com/frameworkium/core/common/reporting/TestIdUtils.java // public class TestIdUtils { // // private TestIdUtils() { // // hide default constructor for this util class // } // // /** // * Get TMS Link or Issue ID value. // * // * @param iMethod the {@link IMethodInstance} to check for test ID annotations. // * @return Optional of either the {@link TmsLink} or {@link Issue} value. // * @throws IllegalStateException if {@link TmsLink} and {@link Issue} // * are specified inconstantly. // * @deprecated Use // * {@link TestIdUtils#getIssueOrTmsLinkValues(IMethodInstance)} instead // */ // @Deprecated // public static Optional<String> getIssueOrTmsLinkValue(IMethodInstance iMethod) { // Method method = iMethod.getMethod().getConstructorOrMethod().getMethod(); // return getIssueOrTmsLinkValue(method); // } // // /** // * Get {@link TmsLink} or {@link Issue} for a method. // * If both are specified it will return jus the {@link TmsLink} value. // * // * @param method the method to check for test ID annotations. // * @return Optional of the {@link TmsLink} or {@link Issue} value. // * @deprecated Use // * {@link TestIdUtils#getIssueOrTmsLinkValues(Method)} instead. // */ // @Deprecated // public static Optional<String> getIssueOrTmsLinkValue(Method method) { // TmsLink tcIdAnnotation = method.getAnnotation(TmsLink.class); // Issue issueAnnotation = method.getAnnotation(Issue.class); // // if (nonNull(tcIdAnnotation)) { // return Optional.of(tcIdAnnotation.value()); // } else if (nonNull(issueAnnotation)) { // return Optional.of(issueAnnotation.value()); // } else { // return Optional.empty(); // } // } // // /** // * Get list of {@link TmsLink} or {@link Issue}. // * // * @param iMethod the {@link IMethodInstance} to check for test ID annotations. // * @return List of either the {@link TmsLink} or {@link Issue} value. // * @throws IllegalStateException if {@link TmsLink} and {@link Issue} // * are specified inconstantly. // */ // public static List<String> getIssueOrTmsLinkValues(IMethodInstance iMethod) { // Method method = iMethod.getMethod().getConstructorOrMethod().getMethod(); // return getIssueOrTmsLinkValues(method); // } // // /** // * Get a list of {@link TmsLink} or {@link Issue} for a method. // * If both are specified it will return just the list of {@link TmsLink} values. // * // * @param method the method to check for test Id annotations. // * @return List of {@link TmsLink} or {@link Issue} values. // */ // public static List<String> getIssueOrTmsLinkValues(Method method) { // TmsLink[] tcIdAnnotations = method.getAnnotationsByType(TmsLink.class); // Issue[] issueAnnotations = method.getAnnotationsByType(Issue.class); // if (tcIdAnnotations.length > 0) { // return Stream.of(tcIdAnnotations).map(TmsLink::value).collect(Collectors.toList()); // } // if (issueAnnotations.length > 0) { // return Stream.of(issueAnnotations).map(Issue::value).collect(Collectors.toList()); // } // return Collections.emptyList(); // } // } // Path: src/main/java/com/frameworkium/core/common/listeners/MethodInterceptor.java import static com.frameworkium.core.common.properties.Property.JIRA_URL; import static com.frameworkium.core.common.properties.Property.JQL_QUERY; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; import com.frameworkium.core.common.reporting.TestIdUtils; import com.frameworkium.core.common.reporting.jira.service.Search; import java.lang.reflect.Method; import java.util.List; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.IMethodInstance; import org.testng.IMethodInterceptor; import org.testng.ITestContext; package com.frameworkium.core.common.listeners; public class MethodInterceptor implements IMethodInterceptor { private static final Logger logger = LogManager.getLogger(); @Override public List<IMethodInstance> intercept( List<IMethodInstance> methods, ITestContext context) { return filterTestsToRunByJQL(methods); } private List<IMethodInstance> filterTestsToRunByJQL( List<IMethodInstance> methodsToBeFiltered) { if (!(JQL_QUERY.isSpecified() && JIRA_URL.isSpecified())) { // Can't run the JQL without both JIRA_URL and JQL_QUERY return methodsToBeFiltered; } logger.info("Filtering specified tests to run with JQL query results"); List<String> testIDsFromJQL = new Search(JQL_QUERY.getValue()).getKeys(); List<IMethodInstance> methodsToRun = methodsToBeFiltered.stream()
.filter(m -> TestIdUtils.getIssueOrTmsLinkValue(m).isPresent())
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/capture/model/message/CreateScreenshot.java
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Command.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Command { // // public String action; // public String using; // public String value; // // public Command(String action, String using, String value) { // this.action = action; // this.using = using; // this.value = value; // } // // public Command(String action, WebElement element) { // this.action = action; // setUsingAndValue(element); // } // // private void setUsingAndValue(WebElement element) { // // TODO: Improve this. Use hacky solution in LoggingListener? // if (Driver.isNative()) { // this.using = "n/a"; // this.value = "n/a"; // } else { // if (StringUtils.isNotBlank(element.getAttribute("id"))) { // this.using = "id"; // this.value = element.getAttribute("id"); // } else if (!(element.getText()).isEmpty()) { // this.using = "linkText"; // this.value = element.getText(); // } else if (!element.getTagName().isEmpty()) { // this.using = "css"; // this.value = element.getTagName() + "." // + element.getAttribute("class").replace(" ", "."); // } else { // // must be something weird // this.using = "n/a"; // this.value = "n/a"; // } // } // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Command; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public class CreateScreenshot { private static final Logger logger = LogManager.getLogger();
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Command.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Command { // // public String action; // public String using; // public String value; // // public Command(String action, String using, String value) { // this.action = action; // this.using = using; // this.value = value; // } // // public Command(String action, WebElement element) { // this.action = action; // setUsingAndValue(element); // } // // private void setUsingAndValue(WebElement element) { // // TODO: Improve this. Use hacky solution in LoggingListener? // if (Driver.isNative()) { // this.using = "n/a"; // this.value = "n/a"; // } else { // if (StringUtils.isNotBlank(element.getAttribute("id"))) { // this.using = "id"; // this.value = element.getAttribute("id"); // } else if (!(element.getText()).isEmpty()) { // this.using = "linkText"; // this.value = element.getText(); // } else if (!element.getTagName().isEmpty()) { // this.using = "css"; // this.value = element.getTagName() + "." // + element.getAttribute("class").replace(" ", "."); // } else { // // must be something weird // this.using = "n/a"; // this.value = "n/a"; // } // } // } // } // Path: src/main/java/com/frameworkium/core/ui/capture/model/message/CreateScreenshot.java import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Command; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public class CreateScreenshot { private static final Logger logger = LogManager.getLogger();
public Command command;
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/capture/model/message/CreateExecution.java
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Browser.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Browser { // // public String name; // public String version; // public String device; // public String platform; // public String platformVersion; // // /** // * Create browser object. // */ // public Browser() { // // Optional<String> userAgent = UITestLifecycle.get().getUserAgent(); // if (userAgent.isPresent() && !userAgent.get().isEmpty()) { // UserAgentStringParser uaParser = UADetectorServiceFactory.getResourceModuleParser(); // ReadableUserAgent agent = uaParser.parse(userAgent.get()); // // this.name = agent.getName(); // this.version = agent.getVersionNumber().toVersionString(); // this.device = agent.getDeviceCategory().getName(); // this.platform = agent.getOperatingSystem().getName(); // this.platformVersion = agent.getOperatingSystem().getVersionNumber().toVersionString(); // // } else { // // Fall-back to the Property class // if (BROWSER.isSpecified()) { // this.name = BROWSER.getValue().toLowerCase(); // } else { // this.name = DriverSetup.DEFAULT_BROWSER.toString(); // } // if (BROWSER_VERSION.isSpecified()) { // this.version = BROWSER_VERSION.getValue(); // } // if (DEVICE.isSpecified()) { // this.device = DEVICE.getValue(); // } // if (PLATFORM.isSpecified()) { // this.platform = PLATFORM.getValue(); // } // if (PLATFORM_VERSION.isSpecified()) { // this.platformVersion = PLATFORM_VERSION.getValue(); // } // } // } // // } // // Path: src/main/java/com/frameworkium/core/ui/capture/model/SoftwareUnderTest.java // public class SoftwareUnderTest { // // public String name; // public String version; // // /** // * Software under test object. // */ // public SoftwareUnderTest() { // if (SUT_NAME.isSpecified()) { // this.name = SUT_NAME.getValue(); // } // if (SUT_VERSION.isSpecified()) { // this.version = SUT_VERSION.getValue(); // } // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Browser; import com.frameworkium.core.ui.capture.model.SoftwareUnderTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public final class CreateExecution { private static final Logger logger = LogManager.getLogger(); public String testID;
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Browser.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Browser { // // public String name; // public String version; // public String device; // public String platform; // public String platformVersion; // // /** // * Create browser object. // */ // public Browser() { // // Optional<String> userAgent = UITestLifecycle.get().getUserAgent(); // if (userAgent.isPresent() && !userAgent.get().isEmpty()) { // UserAgentStringParser uaParser = UADetectorServiceFactory.getResourceModuleParser(); // ReadableUserAgent agent = uaParser.parse(userAgent.get()); // // this.name = agent.getName(); // this.version = agent.getVersionNumber().toVersionString(); // this.device = agent.getDeviceCategory().getName(); // this.platform = agent.getOperatingSystem().getName(); // this.platformVersion = agent.getOperatingSystem().getVersionNumber().toVersionString(); // // } else { // // Fall-back to the Property class // if (BROWSER.isSpecified()) { // this.name = BROWSER.getValue().toLowerCase(); // } else { // this.name = DriverSetup.DEFAULT_BROWSER.toString(); // } // if (BROWSER_VERSION.isSpecified()) { // this.version = BROWSER_VERSION.getValue(); // } // if (DEVICE.isSpecified()) { // this.device = DEVICE.getValue(); // } // if (PLATFORM.isSpecified()) { // this.platform = PLATFORM.getValue(); // } // if (PLATFORM_VERSION.isSpecified()) { // this.platformVersion = PLATFORM_VERSION.getValue(); // } // } // } // // } // // Path: src/main/java/com/frameworkium/core/ui/capture/model/SoftwareUnderTest.java // public class SoftwareUnderTest { // // public String name; // public String version; // // /** // * Software under test object. // */ // public SoftwareUnderTest() { // if (SUT_NAME.isSpecified()) { // this.name = SUT_NAME.getValue(); // } // if (SUT_VERSION.isSpecified()) { // this.version = SUT_VERSION.getValue(); // } // } // } // Path: src/main/java/com/frameworkium/core/ui/capture/model/message/CreateExecution.java import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Browser; import com.frameworkium.core.ui.capture.model.SoftwareUnderTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public final class CreateExecution { private static final Logger logger = LogManager.getLogger(); public String testID;
public Browser browser;
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/capture/model/message/CreateExecution.java
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Browser.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Browser { // // public String name; // public String version; // public String device; // public String platform; // public String platformVersion; // // /** // * Create browser object. // */ // public Browser() { // // Optional<String> userAgent = UITestLifecycle.get().getUserAgent(); // if (userAgent.isPresent() && !userAgent.get().isEmpty()) { // UserAgentStringParser uaParser = UADetectorServiceFactory.getResourceModuleParser(); // ReadableUserAgent agent = uaParser.parse(userAgent.get()); // // this.name = agent.getName(); // this.version = agent.getVersionNumber().toVersionString(); // this.device = agent.getDeviceCategory().getName(); // this.platform = agent.getOperatingSystem().getName(); // this.platformVersion = agent.getOperatingSystem().getVersionNumber().toVersionString(); // // } else { // // Fall-back to the Property class // if (BROWSER.isSpecified()) { // this.name = BROWSER.getValue().toLowerCase(); // } else { // this.name = DriverSetup.DEFAULT_BROWSER.toString(); // } // if (BROWSER_VERSION.isSpecified()) { // this.version = BROWSER_VERSION.getValue(); // } // if (DEVICE.isSpecified()) { // this.device = DEVICE.getValue(); // } // if (PLATFORM.isSpecified()) { // this.platform = PLATFORM.getValue(); // } // if (PLATFORM_VERSION.isSpecified()) { // this.platformVersion = PLATFORM_VERSION.getValue(); // } // } // } // // } // // Path: src/main/java/com/frameworkium/core/ui/capture/model/SoftwareUnderTest.java // public class SoftwareUnderTest { // // public String name; // public String version; // // /** // * Software under test object. // */ // public SoftwareUnderTest() { // if (SUT_NAME.isSpecified()) { // this.name = SUT_NAME.getValue(); // } // if (SUT_VERSION.isSpecified()) { // this.version = SUT_VERSION.getValue(); // } // } // }
import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Browser; import com.frameworkium.core.ui.capture.model.SoftwareUnderTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public final class CreateExecution { private static final Logger logger = LogManager.getLogger(); public String testID; public Browser browser;
// Path: src/main/java/com/frameworkium/core/ui/capture/model/Browser.java // @JsonInclude(JsonInclude.Include.NON_NULL) // public class Browser { // // public String name; // public String version; // public String device; // public String platform; // public String platformVersion; // // /** // * Create browser object. // */ // public Browser() { // // Optional<String> userAgent = UITestLifecycle.get().getUserAgent(); // if (userAgent.isPresent() && !userAgent.get().isEmpty()) { // UserAgentStringParser uaParser = UADetectorServiceFactory.getResourceModuleParser(); // ReadableUserAgent agent = uaParser.parse(userAgent.get()); // // this.name = agent.getName(); // this.version = agent.getVersionNumber().toVersionString(); // this.device = agent.getDeviceCategory().getName(); // this.platform = agent.getOperatingSystem().getName(); // this.platformVersion = agent.getOperatingSystem().getVersionNumber().toVersionString(); // // } else { // // Fall-back to the Property class // if (BROWSER.isSpecified()) { // this.name = BROWSER.getValue().toLowerCase(); // } else { // this.name = DriverSetup.DEFAULT_BROWSER.toString(); // } // if (BROWSER_VERSION.isSpecified()) { // this.version = BROWSER_VERSION.getValue(); // } // if (DEVICE.isSpecified()) { // this.device = DEVICE.getValue(); // } // if (PLATFORM.isSpecified()) { // this.platform = PLATFORM.getValue(); // } // if (PLATFORM_VERSION.isSpecified()) { // this.platformVersion = PLATFORM_VERSION.getValue(); // } // } // } // // } // // Path: src/main/java/com/frameworkium/core/ui/capture/model/SoftwareUnderTest.java // public class SoftwareUnderTest { // // public String name; // public String version; // // /** // * Software under test object. // */ // public SoftwareUnderTest() { // if (SUT_NAME.isSpecified()) { // this.name = SUT_NAME.getValue(); // } // if (SUT_VERSION.isSpecified()) { // this.version = SUT_VERSION.getValue(); // } // } // } // Path: src/main/java/com/frameworkium/core/ui/capture/model/message/CreateExecution.java import com.fasterxml.jackson.annotation.JsonInclude; import com.frameworkium.core.ui.capture.model.Browser; import com.frameworkium.core.ui.capture.model.SoftwareUnderTest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; package com.frameworkium.core.ui.capture.model.message; @JsonInclude(JsonInclude.Include.NON_NULL) public final class CreateExecution { private static final Logger logger = LogManager.getLogger(); public String testID; public Browser browser;
public SoftwareUnderTest softwareUnderTest;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/constant/BookerEndpoint.java // public enum BookerEndpoint implements Endpoint { // // BASE_URI("https://restful-booker.herokuapp.com"), // PING("/ping"), // BOOKING("/booking"), // BOOKING_ID("/booking/%d"), // AUTH("/auth"); // // private String url; // // BookerEndpoint(String url) { // this.url = url; // } // // /** // * @param params Arguments referenced by the format specifiers in the url. // * @return A formatted String representing the URL of the given constant. // */ // @Override // public String getUrl(Object... params) { // return String.format(url, params); // } // // }
import com.frameworkium.integration.restfulbooker.api.constant.BookerEndpoint; import com.frameworkium.integration.restfulbooker.api.service.AbstractBookerService; import io.restassured.RestAssured; import io.restassured.specification.ResponseSpecification; import org.apache.http.HttpStatus;
package com.frameworkium.integration.restfulbooker.api.service.ping; public class PingService extends AbstractBookerService { public String ping() {
// Path: src/test/java/com/frameworkium/integration/restfulbooker/api/constant/BookerEndpoint.java // public enum BookerEndpoint implements Endpoint { // // BASE_URI("https://restful-booker.herokuapp.com"), // PING("/ping"), // BOOKING("/booking"), // BOOKING_ID("/booking/%d"), // AUTH("/auth"); // // private String url; // // BookerEndpoint(String url) { // this.url = url; // } // // /** // * @param params Arguments referenced by the format specifiers in the url. // * @return A formatted String representing the URL of the given constant. // */ // @Override // public String getUrl(Object... params) { // return String.format(url, params); // } // // } // Path: src/test/java/com/frameworkium/integration/restfulbooker/api/service/ping/PingService.java import com.frameworkium.integration.restfulbooker.api.constant.BookerEndpoint; import com.frameworkium.integration.restfulbooker.api.service.AbstractBookerService; import io.restassured.RestAssured; import io.restassured.specification.ResponseSpecification; import org.apache.http.HttpStatus; package com.frameworkium.integration.restfulbooker.api.service.ping; public class PingService extends AbstractBookerService { public String ping() {
return get(BookerEndpoint.PING.getUrl())
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/SortableDataTablesPage.java
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.stream.Stream;
package com.frameworkium.integration.theinternet.pages; public class SortableDataTablesPage extends BasePage<SortableDataTablesPage> { @Visible @CacheLookup @FindBy(id = "table1")
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/theinternet/pages/SortableDataTablesPage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.stream.Stream; package com.frameworkium.integration.theinternet.pages; public class SortableDataTablesPage extends BasePage<SortableDataTablesPage> { @Visible @CacheLookup @FindBy(id = "table1")
private OptimisedStreamTable table1;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/theinternet/pages/SortableDataTablesPage.java
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.stream.Stream;
package com.frameworkium.integration.theinternet.pages; public class SortableDataTablesPage extends BasePage<SortableDataTablesPage> { @Visible @CacheLookup @FindBy(id = "table1") private OptimisedStreamTable table1; @CacheLookup @FindBy(id = "table2") private OptimisedStreamTable table2; public static SortableDataTablesPage open() {
// Path: src/main/java/com/frameworkium/core/ui/element/OptimisedStreamTable.java // public class OptimisedStreamTable extends AbstractStreamTable { // // @FindBy(css = "thead > tr > th") // private List<WebElement> headerCells; // // @FindBy(css = "tbody > tr") // private List<WebElement> rows; // // @Override // protected Stream<WebElement> headerCells() { // return headerCells.stream(); // } // // @Override // protected Stream<WebElement> rows() { // return rows.stream(); // } // // @Override // protected By cellLocator() { // return By.cssSelector("td"); // } // // } // // Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/theinternet/pages/SortableDataTablesPage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.element.OptimisedStreamTable; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.stream.Stream; package com.frameworkium.integration.theinternet.pages; public class SortableDataTablesPage extends BasePage<SortableDataTablesPage> { @Visible @CacheLookup @FindBy(id = "table1") private OptimisedStreamTable table1; @CacheLookup @FindBy(id = "table2") private OptimisedStreamTable table2; public static SortableDataTablesPage open() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/wikipedia/tests/EnglishCountiesTest.java
// Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java // public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { // // @Visible // @CacheLookup // @FindBy(css = "table.wikitable") // luckily there's only one // private OptimisedStreamTable listTable; // // public static EnglishCountiesPage open() { // return PageFactory.newInstance(EnglishCountiesPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // Predicate<WebElement> headerLookUp = e -> e.getText().trim().startsWith("County"); // Predicate<WebElement> lookUpCellMatcher = e -> e.getText().trim().equals(countyName); // Predicate<WebElement> targetColHeaderLookup = e -> e.getText().trim().startsWith("Population"); // String population = listTable // .getCellsByLookup(headerLookUp, lookUpCellMatcher, targetColHeaderLookup) // .findFirst() // .orElseThrow(NotFoundException::new) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // public Stream<Integer> densities() { // return listTable // // hard-coded index because headers are now row-span=2 // .getColumn(6) // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java // public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { // // @Visible(checkAtMost = 1) // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") // private List<WebElement> countyColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") // private List<WebElement> populationColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") // private List<WebElement> densityColumn; // // public static EnglishCountiesUsingListsPage open() { // return PageFactory.newInstance(EnglishCountiesUsingListsPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // String population = // populationColumn.get(findCountyIndex(countyName)) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // private int findCountyIndex(String countyName) { // return IntStream.range(0, countyColumn.size()) // .filter(i -> Objects.equals(countyColumn.get(i).getText(), countyName)) // .findFirst() // .orElseThrow(() -> new NoSuchElementException( // "County name '" + countyName + "' not found")); // } // // public Stream<Integer> densities() { // return densityColumn.stream() // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // }
import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesPage; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesUsingListsPage; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.wikipedia.tests; /** * This test demonstrates the different between using StreamTable and Lists * of WebElements. * <p>The trade-off is between readability, maintainability and performance. * <p>The List option is slightly longer and slightly more difficult to maintain, * especially if your table is changing shape (but not header text), however it * is significantly faster. */ @Test public class EnglishCountiesTest extends BaseUITest { public void exploring_english_counties_data_with_stream_table() {
// Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java // public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { // // @Visible // @CacheLookup // @FindBy(css = "table.wikitable") // luckily there's only one // private OptimisedStreamTable listTable; // // public static EnglishCountiesPage open() { // return PageFactory.newInstance(EnglishCountiesPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // Predicate<WebElement> headerLookUp = e -> e.getText().trim().startsWith("County"); // Predicate<WebElement> lookUpCellMatcher = e -> e.getText().trim().equals(countyName); // Predicate<WebElement> targetColHeaderLookup = e -> e.getText().trim().startsWith("Population"); // String population = listTable // .getCellsByLookup(headerLookUp, lookUpCellMatcher, targetColHeaderLookup) // .findFirst() // .orElseThrow(NotFoundException::new) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // public Stream<Integer> densities() { // return listTable // // hard-coded index because headers are now row-span=2 // .getColumn(6) // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java // public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { // // @Visible(checkAtMost = 1) // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") // private List<WebElement> countyColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") // private List<WebElement> populationColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") // private List<WebElement> densityColumn; // // public static EnglishCountiesUsingListsPage open() { // return PageFactory.newInstance(EnglishCountiesUsingListsPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // String population = // populationColumn.get(findCountyIndex(countyName)) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // private int findCountyIndex(String countyName) { // return IntStream.range(0, countyColumn.size()) // .filter(i -> Objects.equals(countyColumn.get(i).getText(), countyName)) // .findFirst() // .orElseThrow(() -> new NoSuchElementException( // "County name '" + countyName + "' not found")); // } // // public Stream<Integer> densities() { // return densityColumn.stream() // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // Path: src/test/java/com/frameworkium/integration/wikipedia/tests/EnglishCountiesTest.java import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesPage; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesUsingListsPage; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.wikipedia.tests; /** * This test demonstrates the different between using StreamTable and Lists * of WebElements. * <p>The trade-off is between readability, maintainability and performance. * <p>The List option is slightly longer and slightly more difficult to maintain, * especially if your table is changing shape (but not header text), however it * is significantly faster. */ @Test public class EnglishCountiesTest extends BaseUITest { public void exploring_english_counties_data_with_stream_table() {
EnglishCountiesPage page = EnglishCountiesPage.open();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/wikipedia/tests/EnglishCountiesTest.java
// Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java // public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { // // @Visible // @CacheLookup // @FindBy(css = "table.wikitable") // luckily there's only one // private OptimisedStreamTable listTable; // // public static EnglishCountiesPage open() { // return PageFactory.newInstance(EnglishCountiesPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // Predicate<WebElement> headerLookUp = e -> e.getText().trim().startsWith("County"); // Predicate<WebElement> lookUpCellMatcher = e -> e.getText().trim().equals(countyName); // Predicate<WebElement> targetColHeaderLookup = e -> e.getText().trim().startsWith("Population"); // String population = listTable // .getCellsByLookup(headerLookUp, lookUpCellMatcher, targetColHeaderLookup) // .findFirst() // .orElseThrow(NotFoundException::new) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // public Stream<Integer> densities() { // return listTable // // hard-coded index because headers are now row-span=2 // .getColumn(6) // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java // public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { // // @Visible(checkAtMost = 1) // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") // private List<WebElement> countyColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") // private List<WebElement> populationColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") // private List<WebElement> densityColumn; // // public static EnglishCountiesUsingListsPage open() { // return PageFactory.newInstance(EnglishCountiesUsingListsPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // String population = // populationColumn.get(findCountyIndex(countyName)) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // private int findCountyIndex(String countyName) { // return IntStream.range(0, countyColumn.size()) // .filter(i -> Objects.equals(countyColumn.get(i).getText(), countyName)) // .findFirst() // .orElseThrow(() -> new NoSuchElementException( // "County name '" + countyName + "' not found")); // } // // public Stream<Integer> densities() { // return densityColumn.stream() // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // }
import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesPage; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesUsingListsPage; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat;
package com.frameworkium.integration.wikipedia.tests; /** * This test demonstrates the different between using StreamTable and Lists * of WebElements. * <p>The trade-off is between readability, maintainability and performance. * <p>The List option is slightly longer and slightly more difficult to maintain, * especially if your table is changing shape (but not header text), however it * is significantly faster. */ @Test public class EnglishCountiesTest extends BaseUITest { public void exploring_english_counties_data_with_stream_table() { EnglishCountiesPage page = EnglishCountiesPage.open(); assertThat(page.populationOf("Cornwall")) .isAtLeast(550_000); // at least two counties have population densities of more than 3000 assertThat(page.densities() .filter(density -> density > 3000) .limit(2) .count()) .isEqualTo(2L); } public void exploring_english_counties_data_with_lists() {
// Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesPage.java // public class EnglishCountiesPage extends BasePage<EnglishCountiesPage> { // // @Visible // @CacheLookup // @FindBy(css = "table.wikitable") // luckily there's only one // private OptimisedStreamTable listTable; // // public static EnglishCountiesPage open() { // return PageFactory.newInstance(EnglishCountiesPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // Predicate<WebElement> headerLookUp = e -> e.getText().trim().startsWith("County"); // Predicate<WebElement> lookUpCellMatcher = e -> e.getText().trim().equals(countyName); // Predicate<WebElement> targetColHeaderLookup = e -> e.getText().trim().startsWith("Population"); // String population = listTable // .getCellsByLookup(headerLookUp, lookUpCellMatcher, targetColHeaderLookup) // .findFirst() // .orElseThrow(NotFoundException::new) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // public Stream<Integer> densities() { // return listTable // // hard-coded index because headers are now row-span=2 // .getColumn(6) // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java // public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { // // @Visible(checkAtMost = 1) // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") // private List<WebElement> countyColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") // private List<WebElement> populationColumn; // // @CacheLookup // @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") // private List<WebElement> densityColumn; // // public static EnglishCountiesUsingListsPage open() { // return PageFactory.newInstance(EnglishCountiesUsingListsPage.class, // "https://en.wikipedia.org/wiki/List_of_ceremonial_counties_of_England"); // } // // public int populationOf(String countyName) { // String population = // populationColumn.get(findCountyIndex(countyName)) // .getText() // .replaceAll(",", ""); // return Integer.parseInt(population); // } // // private int findCountyIndex(String countyName) { // return IntStream.range(0, countyColumn.size()) // .filter(i -> Objects.equals(countyColumn.get(i).getText(), countyName)) // .findFirst() // .orElseThrow(() -> new NoSuchElementException( // "County name '" + countyName + "' not found")); // } // // public Stream<Integer> densities() { // return densityColumn.stream() // .map(WebElement::getText) // .map(density -> density.replaceAll(",", "")) // .map(Integer::parseInt); // } // // } // Path: src/test/java/com/frameworkium/integration/wikipedia/tests/EnglishCountiesTest.java import com.frameworkium.core.ui.tests.BaseUITest; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesPage; import com.frameworkium.integration.wikipedia.pages.EnglishCountiesUsingListsPage; import org.testng.annotations.Test; import static com.google.common.truth.Truth.assertThat; package com.frameworkium.integration.wikipedia.tests; /** * This test demonstrates the different between using StreamTable and Lists * of WebElements. * <p>The trade-off is between readability, maintainability and performance. * <p>The List option is slightly longer and slightly more difficult to maintain, * especially if your table is changing shape (but not header text), however it * is significantly faster. */ @Test public class EnglishCountiesTest extends BaseUITest { public void exploring_english_counties_data_with_stream_table() { EnglishCountiesPage page = EnglishCountiesPage.open(); assertThat(page.populationOf("Cornwall")) .isAtLeast(550_000); // at least two counties have population densities of more than 3000 assertThat(page.densities() .filter(density -> density > 3000) .limit(2) .count()) .isEqualTo(2L); } public void exploring_english_counties_data_with_lists() {
EnglishCountiesUsingListsPage page = EnglishCountiesUsingListsPage.open();
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/common/reporting/allure/AllureProperties.java
// Path: src/main/java/com/frameworkium/core/ui/UITestLifecycle.java // public class UITestLifecycle { // // private static final Duration DEFAULT_TIMEOUT = Duration.of(10, SECONDS); // // private static final ThreadLocal<ScreenshotCapture> capture = new ThreadLocal<>(); // private static final ThreadLocal<Wait<WebDriver>> wait = new ThreadLocal<>(); // private static final ThreadLocal<UITestLifecycle> uiTestLifecycle = // ThreadLocal.withInitial(UITestLifecycle::new); // // private static DriverLifecycle driverLifecycle; // private static String userAgent; // // /** // * @return a ThreadLocal instance of {@link UITestLifecycle} // */ // public static UITestLifecycle get() { // return uiTestLifecycle.get(); // } // // /** // * @return check to see if class initialised correctly. // */ // public boolean isInitialised() { // return wait.get() != null; // } // // /** // * Run this before the test suite to initialise a pool of drivers. // */ // public void beforeSuite() { // if (Property.REUSE_BROWSER.getBoolean()) { // driverLifecycle = // new MultiUseDriverLifecycle( // Property.THREADS.getIntWithDefault(1)); // } else { // driverLifecycle = new SingleUseDriverLifecycle(); // } // driverLifecycle.initDriverPool(DriverSetup::instantiateDriver); // } // // /** // * Run this before each test method to initialise the // * browser, wait, capture, and user agent. // * // * <p>This is useful for times when the testMethod does not contain the required // * test name e.g. using data providers for BDD. // * // * @param testName the test name for Capture // */ // public void beforeTestMethod(String testName) { // driverLifecycle.initBrowserBeforeTest(DriverSetup::instantiateDriver); // // wait.set(newWaitWithTimeout(DEFAULT_TIMEOUT)); // // if (ScreenshotCapture.isRequired()) { // capture.set(new ScreenshotCapture(testName)); // } // // if (userAgent == null) { // userAgent = UserAgent.getUserAgent((JavascriptExecutor) getWebDriver()); // } // } // // /** // * @param testMethod the method about to run, used to extract the test name // * @see #beforeTestMethod(String) // */ // public void beforeTestMethod(Method testMethod) { // beforeTestMethod(getTestNameForCapture(testMethod)); // } // // private String getTestNameForCapture(Method testMethod) { // Optional<String> testID = TestIdUtils.getIssueOrTmsLinkValue(testMethod); // if (!testID.isPresent() || testID.get().isEmpty()) { // testID = Optional.of(StringUtils.abbreviate(testMethod.getName(), 20)); // } // return testID.orElse("n/a"); // } // // /** // * Run after each test method to clear or tear down the browser // */ // public void afterTestMethod() { // driverLifecycle.tearDownDriver(); // } // // /** // * Run after the entire test suite to: // * clear down the browser pool, send remaining screenshots to Capture // * and create properties for Allure. // */ // public void afterTestSuite() { // driverLifecycle.tearDownDriverPool(); // ScreenshotCapture.processRemainingBacklog(); // AllureProperties.createUI(); // } // // /** // * @return new Wait with default timeout. // * @deprecated use {@code UITestLifecycle.get().getWait()} instead. // */ // @Deprecated // public Wait<WebDriver> newDefaultWait() { // return newWaitWithTimeout(DEFAULT_TIMEOUT); // } // // /** // * @param timeout timeout for the new Wait // * @return a Wait with the given timeout // */ // public Wait<WebDriver> newWaitWithTimeout(Duration timeout) { // return new FluentWait<>(getWebDriver()) // .withTimeout(timeout) // .ignoring(NoSuchElementException.class) // .ignoring(StaleElementReferenceException.class); // } // // public WebDriver getWebDriver() { // return driverLifecycle.getWebDriver(); // } // // public ScreenshotCapture getCapture() { // return capture.get(); // } // // public Wait<WebDriver> getWait() { // return wait.get(); // } // // /** // * @return the user agent of the browser in the first UI test to run. // */ // public Optional<String> getUserAgent() { // return Optional.ofNullable(userAgent); // } // // /** // * @return the session ID of the remote WebDriver // */ // public String getRemoteSessionId() { // return Objects.toString(((RemoteWebDriver) getWebDriver()).getSessionId()); // } // }
import static java.util.Objects.nonNull; import com.frameworkium.core.common.properties.Property; import com.frameworkium.core.ui.UITestLifecycle; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger;
private static String obfuscatePasswordValue(Property p) { String key = p.toString(); String value = p.getValue(); if (key.toLowerCase().contains("password")) { return value.replaceAll(".", "*"); } return value; } private static Properties getCommonProps() { Properties props = new Properties(); if (nonNull(System.getenv("BUILD_URL"))) { props.setProperty("CI build URL", System.getenv("BUILD_URL")); } if (nonNull(System.getProperty("config"))) { props.setProperty("Config file", System.getProperty("config")); } if (Property.JIRA_URL.isSpecified()) { final String jiraPattern = Property.JIRA_URL.getValue() + "/browse/%s"; props.setProperty("allure.issues.tracker.pattern", jiraPattern); props.setProperty("allure.tests.management.pattern", jiraPattern); } return props; } private static Properties getUIProperties() { Properties props = new Properties();
// Path: src/main/java/com/frameworkium/core/ui/UITestLifecycle.java // public class UITestLifecycle { // // private static final Duration DEFAULT_TIMEOUT = Duration.of(10, SECONDS); // // private static final ThreadLocal<ScreenshotCapture> capture = new ThreadLocal<>(); // private static final ThreadLocal<Wait<WebDriver>> wait = new ThreadLocal<>(); // private static final ThreadLocal<UITestLifecycle> uiTestLifecycle = // ThreadLocal.withInitial(UITestLifecycle::new); // // private static DriverLifecycle driverLifecycle; // private static String userAgent; // // /** // * @return a ThreadLocal instance of {@link UITestLifecycle} // */ // public static UITestLifecycle get() { // return uiTestLifecycle.get(); // } // // /** // * @return check to see if class initialised correctly. // */ // public boolean isInitialised() { // return wait.get() != null; // } // // /** // * Run this before the test suite to initialise a pool of drivers. // */ // public void beforeSuite() { // if (Property.REUSE_BROWSER.getBoolean()) { // driverLifecycle = // new MultiUseDriverLifecycle( // Property.THREADS.getIntWithDefault(1)); // } else { // driverLifecycle = new SingleUseDriverLifecycle(); // } // driverLifecycle.initDriverPool(DriverSetup::instantiateDriver); // } // // /** // * Run this before each test method to initialise the // * browser, wait, capture, and user agent. // * // * <p>This is useful for times when the testMethod does not contain the required // * test name e.g. using data providers for BDD. // * // * @param testName the test name for Capture // */ // public void beforeTestMethod(String testName) { // driverLifecycle.initBrowserBeforeTest(DriverSetup::instantiateDriver); // // wait.set(newWaitWithTimeout(DEFAULT_TIMEOUT)); // // if (ScreenshotCapture.isRequired()) { // capture.set(new ScreenshotCapture(testName)); // } // // if (userAgent == null) { // userAgent = UserAgent.getUserAgent((JavascriptExecutor) getWebDriver()); // } // } // // /** // * @param testMethod the method about to run, used to extract the test name // * @see #beforeTestMethod(String) // */ // public void beforeTestMethod(Method testMethod) { // beforeTestMethod(getTestNameForCapture(testMethod)); // } // // private String getTestNameForCapture(Method testMethod) { // Optional<String> testID = TestIdUtils.getIssueOrTmsLinkValue(testMethod); // if (!testID.isPresent() || testID.get().isEmpty()) { // testID = Optional.of(StringUtils.abbreviate(testMethod.getName(), 20)); // } // return testID.orElse("n/a"); // } // // /** // * Run after each test method to clear or tear down the browser // */ // public void afterTestMethod() { // driverLifecycle.tearDownDriver(); // } // // /** // * Run after the entire test suite to: // * clear down the browser pool, send remaining screenshots to Capture // * and create properties for Allure. // */ // public void afterTestSuite() { // driverLifecycle.tearDownDriverPool(); // ScreenshotCapture.processRemainingBacklog(); // AllureProperties.createUI(); // } // // /** // * @return new Wait with default timeout. // * @deprecated use {@code UITestLifecycle.get().getWait()} instead. // */ // @Deprecated // public Wait<WebDriver> newDefaultWait() { // return newWaitWithTimeout(DEFAULT_TIMEOUT); // } // // /** // * @param timeout timeout for the new Wait // * @return a Wait with the given timeout // */ // public Wait<WebDriver> newWaitWithTimeout(Duration timeout) { // return new FluentWait<>(getWebDriver()) // .withTimeout(timeout) // .ignoring(NoSuchElementException.class) // .ignoring(StaleElementReferenceException.class); // } // // public WebDriver getWebDriver() { // return driverLifecycle.getWebDriver(); // } // // public ScreenshotCapture getCapture() { // return capture.get(); // } // // public Wait<WebDriver> getWait() { // return wait.get(); // } // // /** // * @return the user agent of the browser in the first UI test to run. // */ // public Optional<String> getUserAgent() { // return Optional.ofNullable(userAgent); // } // // /** // * @return the session ID of the remote WebDriver // */ // public String getRemoteSessionId() { // return Objects.toString(((RemoteWebDriver) getWebDriver()).getSessionId()); // } // } // Path: src/main/java/com/frameworkium/core/common/reporting/allure/AllureProperties.java import static java.util.Objects.nonNull; import com.frameworkium.core.common.properties.Property; import com.frameworkium.core.ui.UITestLifecycle; import java.io.FileOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Map; import java.util.Properties; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; private static String obfuscatePasswordValue(Property p) { String key = p.toString(); String value = p.getValue(); if (key.toLowerCase().contains("password")) { return value.replaceAll(".", "*"); } return value; } private static Properties getCommonProps() { Properties props = new Properties(); if (nonNull(System.getenv("BUILD_URL"))) { props.setProperty("CI build URL", System.getenv("BUILD_URL")); } if (nonNull(System.getProperty("config"))) { props.setProperty("Config file", System.getProperty("config")); } if (Property.JIRA_URL.isSpecified()) { final String jiraPattern = Property.JIRA_URL.getValue() + "/browse/%s"; props.setProperty("allure.issues.tracker.pattern", jiraPattern); props.setProperty("allure.tests.management.pattern", jiraPattern); } return props; } private static Properties getUIProperties() { Properties props = new Properties();
UITestLifecycle.get().getUserAgent()
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/driver/drivers/BrowserStackImpl.java
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/BrowserStack.java // public class BrowserStack { // // private BrowserStack() { // // hide default constructor for this util class // } // // public static URL getURL() throws MalformedURLException { // return new URL(String.format("https://%s:%[email protected]/wd/hub", // System.getenv("BROWSER_STACK_USERNAME"), // System.getenv("BROWSER_STACK_ACCESS_KEY"))); // } // // public static boolean isDesired() { // return BROWSER_STACK.getBoolean(); // } // }
import static com.frameworkium.core.ui.driver.DriverSetup.Platform; import com.frameworkium.core.common.properties.Property; import com.frameworkium.core.ui.driver.AbstractDriver; import com.frameworkium.core.ui.driver.remotes.BrowserStack; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.RemoteWebDriver;
package com.frameworkium.core.ui.driver.drivers; public class BrowserStackImpl extends AbstractDriver { private URL remoteURL; private Platform platform; private Capabilities capabilities; /** * Implementation of driver for BrowserStack. */ public BrowserStackImpl(Platform platform, Capabilities browserCapabilities) { this.platform = platform; capabilities = browserCapabilities; try {
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/BrowserStack.java // public class BrowserStack { // // private BrowserStack() { // // hide default constructor for this util class // } // // public static URL getURL() throws MalformedURLException { // return new URL(String.format("https://%s:%[email protected]/wd/hub", // System.getenv("BROWSER_STACK_USERNAME"), // System.getenv("BROWSER_STACK_ACCESS_KEY"))); // } // // public static boolean isDesired() { // return BROWSER_STACK.getBoolean(); // } // } // Path: src/main/java/com/frameworkium/core/ui/driver/drivers/BrowserStackImpl.java import static com.frameworkium.core.ui.driver.DriverSetup.Platform; import com.frameworkium.core.common.properties.Property; import com.frameworkium.core.ui.driver.AbstractDriver; import com.frameworkium.core.ui.driver.remotes.BrowserStack; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.Capabilities; import org.openqa.selenium.MutableCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.RemoteWebDriver; package com.frameworkium.core.ui.driver.drivers; public class BrowserStackImpl extends AbstractDriver { private URL remoteURL; private Platform platform; private Capabilities capabilities; /** * Implementation of driver for BrowserStack. */ public BrowserStackImpl(Platform platform, Capabilities browserCapabilities) { this.platform = platform; capabilities = browserCapabilities; try {
remoteURL = BrowserStack.getURL();
Frameworkium/frameworkium-core
src/main/java/com/frameworkium/core/ui/listeners/SauceLabsListener.java
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/Sauce.java // public class Sauce { // // private static final SauceOnDemandAuthentication sauceAuth = // new SauceOnDemandAuthentication( // System.getenv("SAUCE_USERNAME"), // System.getenv("SAUCE_ACCESS_KEY")); // // private static final SauceREST client = // new SauceREST( // sauceAuth.getUsername(), // sauceAuth.getAccessKey()); // // public static URL getURL() { // try { // return new URL(String.format( // "https://%s:%[email protected]/wd/hub", // sauceAuth.getUsername(), // sauceAuth.getAccessKey())); // } catch (MalformedURLException e) { // throw new IllegalArgumentException(e); // } // } // // public static boolean isDesired() { // return Property.SAUCE.getBoolean(); // } // // public static void updateJobName(SauceOnDemandSessionIdProvider sessionIdProvider, String name) { // // client.updateJobInfo( // sessionIdProvider.getSessionId(), // ImmutableMap.of("name", name)); // } // // public static void uploadFile(File file) throws IOException { // client.uploadFile(file); // } // // }
import static com.frameworkium.core.common.properties.Property.APP_PATH; import com.frameworkium.core.ui.driver.Driver; import com.frameworkium.core.ui.driver.remotes.Sauce; import com.saucelabs.common.SauceOnDemandSessionIdProvider; import com.saucelabs.testng.SauceOnDemandTestListener; import java.io.File; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.ITestContext; import org.testng.ITestResult;
package com.frameworkium.core.ui.listeners; public class SauceLabsListener extends SauceOnDemandTestListener { private static final Logger logger = LogManager.getLogger();
// Path: src/main/java/com/frameworkium/core/ui/driver/remotes/Sauce.java // public class Sauce { // // private static final SauceOnDemandAuthentication sauceAuth = // new SauceOnDemandAuthentication( // System.getenv("SAUCE_USERNAME"), // System.getenv("SAUCE_ACCESS_KEY")); // // private static final SauceREST client = // new SauceREST( // sauceAuth.getUsername(), // sauceAuth.getAccessKey()); // // public static URL getURL() { // try { // return new URL(String.format( // "https://%s:%[email protected]/wd/hub", // sauceAuth.getUsername(), // sauceAuth.getAccessKey())); // } catch (MalformedURLException e) { // throw new IllegalArgumentException(e); // } // } // // public static boolean isDesired() { // return Property.SAUCE.getBoolean(); // } // // public static void updateJobName(SauceOnDemandSessionIdProvider sessionIdProvider, String name) { // // client.updateJobInfo( // sessionIdProvider.getSessionId(), // ImmutableMap.of("name", name)); // } // // public static void uploadFile(File file) throws IOException { // client.uploadFile(file); // } // // } // Path: src/main/java/com/frameworkium/core/ui/listeners/SauceLabsListener.java import static com.frameworkium.core.common.properties.Property.APP_PATH; import com.frameworkium.core.ui.driver.Driver; import com.frameworkium.core.ui.driver.remotes.Sauce; import com.saucelabs.common.SauceOnDemandSessionIdProvider; import com.saucelabs.testng.SauceOnDemandTestListener; import java.io.File; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.testng.ITestContext; import org.testng.ITestResult; package com.frameworkium.core.ui.listeners; public class SauceLabsListener extends SauceOnDemandTestListener { private static final Logger logger = LogManager.getLogger();
private static final boolean IS_RUNNING_ON_SAUCE_LABS = Sauce.isDesired();
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy;
package com.frameworkium.integration.seleniumhq.pages; public class HomePage extends BasePage<HomePage> { @CacheLookup @Visible
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // } // Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; package com.frameworkium.integration.seleniumhq.pages; public class HomePage extends BasePage<HomePage> { @CacheLookup @Visible
private HeaderComponent header;
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy;
package com.frameworkium.integration.seleniumhq.pages; public class HomePage extends BasePage<HomePage> { @CacheLookup @Visible private HeaderComponent header; @FindBy(css = "button[data-target='#main_navbar']") private WebElement menuLink; public static HomePage open() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // // Path: src/test/java/com/frameworkium/integration/seleniumhq/components/HeaderComponent.java // @FindBy(className = "navbar") // public class HeaderComponent extends HtmlElement { // // @FindBy(css = "#main_navbar [href='/downloads']") // private Link downloadLink; // // public SeleniumDownloadPage clickDownloadLink() { // UITestLifecycle.get().getWait().until(ExpectedConditions.elementToBeClickable(downloadLink)); // downloadLink.click(); // return PageFactory.newInstance(SeleniumDownloadPage.class); // } // // } // Path: src/test/java/com/frameworkium/integration/seleniumhq/pages/HomePage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import com.frameworkium.integration.seleniumhq.components.HeaderComponent; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; package com.frameworkium.integration.seleniumhq.pages; public class HomePage extends BasePage<HomePage> { @CacheLookup @Visible private HeaderComponent header; @FindBy(css = "button[data-target='#main_navbar']") private WebElement menuLink; public static HomePage open() {
return PageFactory.newInstance(
Frameworkium/frameworkium-core
src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // }
import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.Objects; import java.util.stream.IntStream; import java.util.stream.Stream;
package com.frameworkium.integration.wikipedia.pages; /** * This page uses {@link List}s of {@link WebElement}s for the columns we know * that we need. This test is faster than using StreamTable, especially when * running over a grid due to the far fewer page lookups required. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are unlikely to change often. */ public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { @Visible(checkAtMost = 1) @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") private List<WebElement> countyColumn; @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") private List<WebElement> populationColumn; @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") private List<WebElement> densityColumn; public static EnglishCountiesUsingListsPage open() {
// Path: src/main/java/com/frameworkium/core/ui/pages/PageFactory.java // public class PageFactory { // // private static final Logger logger = LogManager.getLogger(); // // protected PageFactory() { // } // // public static <T extends BasePage<T>> T newInstance(Class<T> clazz) { // return instantiatePageObject(clazz).get(); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, Duration timeout) { // return instantiatePageObject(clazz).get(timeout); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url) { // return instantiatePageObject(clazz).get(url); // } // // public static <T extends BasePage<T>> T newInstance( // Class<T> clazz, String url, Duration timeout) { // return instantiatePageObject(clazz).get(url, timeout); // } // // private static <T extends BasePage<T>> T instantiatePageObject(Class<T> clazz) { // try { // return clazz.getDeclaredConstructor().newInstance(); // } catch (InstantiationException | IllegalAccessException // | NoSuchMethodException | InvocationTargetException e) { // logger.fatal("Unable to instantiate PageObject", e); // throw new IllegalStateException("Unable to instantiate PageObject", e); // } // } // } // Path: src/test/java/com/frameworkium/integration/wikipedia/pages/EnglishCountiesUsingListsPage.java import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.CacheLookup; import org.openqa.selenium.support.FindBy; import java.util.List; import java.util.Objects; import java.util.stream.IntStream; import java.util.stream.Stream; package com.frameworkium.integration.wikipedia.pages; /** * This page uses {@link List}s of {@link WebElement}s for the columns we know * that we need. This test is faster than using StreamTable, especially when * running over a grid due to the far fewer page lookups required. * * <p>This is a trade-off between readability, maintainability and performance. * * <p>This approach is great if the table and tests are unlikely to change often. */ public class EnglishCountiesUsingListsPage extends BasePage<EnglishCountiesUsingListsPage> { @Visible(checkAtMost = 1) @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(1)") private List<WebElement> countyColumn; @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(2)") private List<WebElement> populationColumn; @CacheLookup @FindBy(css = "table.wikitable > tbody > tr > td:nth-child(7)") private List<WebElement> densityColumn; public static EnglishCountiesUsingListsPage open() {
return PageFactory.newInstance(EnglishCountiesUsingListsPage.class,
bio4j/bio4j-examples
old-examples/tools/uniprot/SplitUniprotXmlFile.java
// Path: old-examples/CommonData.java // public class CommonData { // // public static final String DATABASE_FOLDER = "bio4jdb"; // // public static final String PROPERTIES_FILE_NAME = "batchInserter.properties"; // public static final String ENTRY_TAG_NAME = "entry"; // public static final String ENTRY_ACCESSION_TAG_NAME = "accession"; // public static final String ENTRY_NAME_TAG_NAME = "name"; // public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified"; // public static final String ENTRY_DATASET_ATTRIBUTE = "dataset"; // public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence"; // // public static final String KEYWORD_TAG_NAME = "keyword"; // public static final String KEYWORD_ID_ATTRIBUTE = "id"; // // public static final String REFERENCE_TAG_NAME = "reference"; // public static final String CITATION_TAG_NAME = "citation"; // // public static final String ORGANISM_TAG_NAME = "organism"; // public static final String ORGANISM_NAME_TAG_NAME = "name"; // public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type"; // public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific"; // public static final String ORGANISM_COMMON_NAME_TYPE = "common"; // public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym"; // // public static final String DB_REFERENCE_TAG_NAME = "dbReference"; // public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type"; // public static final String DB_REFERENCE_ID_ATTRIBUTE = "id"; // public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value"; // public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property"; // // public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro"; // public static final String INTERPRO_ENTRY_NAME = "entry name"; // // public static final String GO_DB_REFERENCE_TYPE = "GO"; // public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence"; // // public static final String SEQUENCE_MASS_ATTRIBUTE = "mass"; // public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length"; // public static final String PROTEIN_TAG_NAME = "protein"; // public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName"; // public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName"; // public static final String GENE_TAG_NAME = "gene"; // public static final String GENE_NAME_TAG_NAME = "name"; // public static final String COMMENT_TAG_NAME = "comment"; // public static final String COMMENT_TYPE_ATTRIBUTE = "type"; // public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products"; // public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution"; // public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation"; // public static final String LOCATION_TAG_NAME = "location"; // public static final String COMMENT_TEXT_TAG_NAME = "text"; // public static final String FEATURE_TAG_NAME = "feature"; // public static final String FEATURE_TYPE_ATTRIBUTE = "type"; // public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description"; // public static final String STATUS_ATTRIBUTE = "status"; // public static final String FEATURE_REF_ATTRIBUTE = "ref"; // public static final String FEATURE_ID_ATTRIBUTE = "id"; // public static final String EVIDENCE_ATTRIBUTE = "evidence"; // public static final String FEATURE_LOCATION_TAG_NAME = "location"; // public static final String FEATURE_ORIGINAL_TAG_NAME = "original"; // public static final String FEATURE_VARIATION_TAG_NAME = "variation"; // public static final String FEATURE_POSITION_TAG_NAME = "position"; // public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin"; // public static final String FEATURE_LOCATION_END_TAG_NAME = "end"; // public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position"; // public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position"; // // // }
import java.io.*; import com.ohnosequences.bio4j.CommonData;
/* * Copyright (C) 2010-2011 "Bio4j" * * This file is part of Bio4j * * Bio4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.ohnosequences.bio4j.tools.uniprot; /** * * @author Pablo Pareja Tobes <[email protected]> */ public class SplitUniprotXmlFile { public static void main(String[] args) { if (args.length != 2) { System.out.println("This program expects two parameters: \n" + "1. Uniprot xml input file\n" + "2. Number of entries per resulting part file\n"); } else { int numberOfEntries = Integer.parseInt(args[1]); int currentFile = 1; int currentEntry = 1; File inFile = new File(args[0]); String prefixOutFile = args[0].split("\\.")[0]; try { BufferedWriter outBuff = new BufferedWriter(new FileWriter(new File(prefixOutFile + currentFile + ".xml"))); outBuff.write("<entries>\n"); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line; while ((line = reader.readLine()) != null) {
// Path: old-examples/CommonData.java // public class CommonData { // // public static final String DATABASE_FOLDER = "bio4jdb"; // // public static final String PROPERTIES_FILE_NAME = "batchInserter.properties"; // public static final String ENTRY_TAG_NAME = "entry"; // public static final String ENTRY_ACCESSION_TAG_NAME = "accession"; // public static final String ENTRY_NAME_TAG_NAME = "name"; // public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified"; // public static final String ENTRY_DATASET_ATTRIBUTE = "dataset"; // public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence"; // // public static final String KEYWORD_TAG_NAME = "keyword"; // public static final String KEYWORD_ID_ATTRIBUTE = "id"; // // public static final String REFERENCE_TAG_NAME = "reference"; // public static final String CITATION_TAG_NAME = "citation"; // // public static final String ORGANISM_TAG_NAME = "organism"; // public static final String ORGANISM_NAME_TAG_NAME = "name"; // public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type"; // public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific"; // public static final String ORGANISM_COMMON_NAME_TYPE = "common"; // public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym"; // // public static final String DB_REFERENCE_TAG_NAME = "dbReference"; // public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type"; // public static final String DB_REFERENCE_ID_ATTRIBUTE = "id"; // public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value"; // public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property"; // // public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro"; // public static final String INTERPRO_ENTRY_NAME = "entry name"; // // public static final String GO_DB_REFERENCE_TYPE = "GO"; // public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence"; // // public static final String SEQUENCE_MASS_ATTRIBUTE = "mass"; // public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length"; // public static final String PROTEIN_TAG_NAME = "protein"; // public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName"; // public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName"; // public static final String GENE_TAG_NAME = "gene"; // public static final String GENE_NAME_TAG_NAME = "name"; // public static final String COMMENT_TAG_NAME = "comment"; // public static final String COMMENT_TYPE_ATTRIBUTE = "type"; // public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products"; // public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution"; // public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation"; // public static final String LOCATION_TAG_NAME = "location"; // public static final String COMMENT_TEXT_TAG_NAME = "text"; // public static final String FEATURE_TAG_NAME = "feature"; // public static final String FEATURE_TYPE_ATTRIBUTE = "type"; // public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description"; // public static final String STATUS_ATTRIBUTE = "status"; // public static final String FEATURE_REF_ATTRIBUTE = "ref"; // public static final String FEATURE_ID_ATTRIBUTE = "id"; // public static final String EVIDENCE_ATTRIBUTE = "evidence"; // public static final String FEATURE_LOCATION_TAG_NAME = "location"; // public static final String FEATURE_ORIGINAL_TAG_NAME = "original"; // public static final String FEATURE_VARIATION_TAG_NAME = "variation"; // public static final String FEATURE_POSITION_TAG_NAME = "position"; // public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin"; // public static final String FEATURE_LOCATION_END_TAG_NAME = "end"; // public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position"; // public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position"; // // // } // Path: old-examples/tools/uniprot/SplitUniprotXmlFile.java import java.io.*; import com.ohnosequences.bio4j.CommonData; /* * Copyright (C) 2010-2011 "Bio4j" * * This file is part of Bio4j * * Bio4j is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.ohnosequences.bio4j.tools.uniprot; /** * * @author Pablo Pareja Tobes <[email protected]> */ public class SplitUniprotXmlFile { public static void main(String[] args) { if (args.length != 2) { System.out.println("This program expects two parameters: \n" + "1. Uniprot xml input file\n" + "2. Number of entries per resulting part file\n"); } else { int numberOfEntries = Integer.parseInt(args[1]); int currentFile = 1; int currentEntry = 1; File inFile = new File(args[0]); String prefixOutFile = args[0].split("\\.")[0]; try { BufferedWriter outBuff = new BufferedWriter(new FileWriter(new File(prefixOutFile + currentFile + ".xml"))); outBuff.write("<entries>\n"); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line; while ((line = reader.readLine()) != null) {
if (line.trim().startsWith("<" + CommonData.ENTRY_TAG_NAME)) {
bio4j/bio4j-examples
old-examples/tools/SplitUniprotXmlFile.java
// Path: old-examples/CommonData.java // public class CommonData { // // public static final String DATABASE_FOLDER = "bio4jdb"; // // public static final String PROPERTIES_FILE_NAME = "batchInserter.properties"; // public static final String ENTRY_TAG_NAME = "entry"; // public static final String ENTRY_ACCESSION_TAG_NAME = "accession"; // public static final String ENTRY_NAME_TAG_NAME = "name"; // public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified"; // public static final String ENTRY_DATASET_ATTRIBUTE = "dataset"; // public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence"; // // public static final String KEYWORD_TAG_NAME = "keyword"; // public static final String KEYWORD_ID_ATTRIBUTE = "id"; // // public static final String REFERENCE_TAG_NAME = "reference"; // public static final String CITATION_TAG_NAME = "citation"; // // public static final String ORGANISM_TAG_NAME = "organism"; // public static final String ORGANISM_NAME_TAG_NAME = "name"; // public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type"; // public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific"; // public static final String ORGANISM_COMMON_NAME_TYPE = "common"; // public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym"; // // public static final String DB_REFERENCE_TAG_NAME = "dbReference"; // public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type"; // public static final String DB_REFERENCE_ID_ATTRIBUTE = "id"; // public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value"; // public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property"; // // public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro"; // public static final String INTERPRO_ENTRY_NAME = "entry name"; // // public static final String GO_DB_REFERENCE_TYPE = "GO"; // public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence"; // // public static final String SEQUENCE_MASS_ATTRIBUTE = "mass"; // public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length"; // public static final String PROTEIN_TAG_NAME = "protein"; // public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName"; // public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName"; // public static final String GENE_TAG_NAME = "gene"; // public static final String GENE_NAME_TAG_NAME = "name"; // public static final String COMMENT_TAG_NAME = "comment"; // public static final String COMMENT_TYPE_ATTRIBUTE = "type"; // public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products"; // public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution"; // public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation"; // public static final String LOCATION_TAG_NAME = "location"; // public static final String COMMENT_TEXT_TAG_NAME = "text"; // public static final String FEATURE_TAG_NAME = "feature"; // public static final String FEATURE_TYPE_ATTRIBUTE = "type"; // public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description"; // public static final String STATUS_ATTRIBUTE = "status"; // public static final String FEATURE_REF_ATTRIBUTE = "ref"; // public static final String FEATURE_ID_ATTRIBUTE = "id"; // public static final String EVIDENCE_ATTRIBUTE = "evidence"; // public static final String FEATURE_LOCATION_TAG_NAME = "location"; // public static final String FEATURE_ORIGINAL_TAG_NAME = "original"; // public static final String FEATURE_VARIATION_TAG_NAME = "variation"; // public static final String FEATURE_POSITION_TAG_NAME = "position"; // public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin"; // public static final String FEATURE_LOCATION_END_TAG_NAME = "end"; // public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position"; // public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position"; // // // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import com.ohnosequences.bio4j.CommonData;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ohnosequences.bio4j.tools; /** * * @author Pablo Pareja Tobes <[email protected]> */ public class SplitUniprotXmlFile { public static void main(String[] args) { if (args.length != 2) { System.out.println("This program expects two parameters: \n" + "1. Uniprot xml input file\n" + "2. Number of entries per resulting part file\n"); } else { int numberOfEntries = Integer.parseInt(args[1]); int currentFile = 1; int currentEntry = 1; File inFile = new File(args[0]); String prefixOutFile = args[0].split("\\.")[0]; try { BufferedWriter outBuff = new BufferedWriter(new FileWriter(new File(prefixOutFile + currentFile + ".xml"))); outBuff.write("<entries>\n"); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line = null; while ((line = reader.readLine()) != null) {
// Path: old-examples/CommonData.java // public class CommonData { // // public static final String DATABASE_FOLDER = "bio4jdb"; // // public static final String PROPERTIES_FILE_NAME = "batchInserter.properties"; // public static final String ENTRY_TAG_NAME = "entry"; // public static final String ENTRY_ACCESSION_TAG_NAME = "accession"; // public static final String ENTRY_NAME_TAG_NAME = "name"; // public static final String ENTRY_MODIFIED_DATE_ATTRIBUTE = "modified"; // public static final String ENTRY_DATASET_ATTRIBUTE = "dataset"; // public static final String ENTRY_SEQUENCE_TAG_NAME = "sequence"; // // public static final String KEYWORD_TAG_NAME = "keyword"; // public static final String KEYWORD_ID_ATTRIBUTE = "id"; // // public static final String REFERENCE_TAG_NAME = "reference"; // public static final String CITATION_TAG_NAME = "citation"; // // public static final String ORGANISM_TAG_NAME = "organism"; // public static final String ORGANISM_NAME_TAG_NAME = "name"; // public static final String ORGANISM_NAME_TYPE_ATTRIBUTE = "type"; // public static final String ORGANISM_SCIENTIFIC_NAME_TYPE = "scientific"; // public static final String ORGANISM_COMMON_NAME_TYPE = "common"; // public static final String ORGANISM_SYNONYM_NAME_TYPE = "synonym"; // // public static final String DB_REFERENCE_TAG_NAME = "dbReference"; // public static final String DB_REFERENCE_TYPE_ATTRIBUTE = "type"; // public static final String DB_REFERENCE_ID_ATTRIBUTE = "id"; // public static final String DB_REFERENCE_VALUE_ATTRIBUTE = "value"; // public static final String DB_REFERENCE_PROPERTY_TAG_NAME = "property"; // // public static final String INTERPRO_DB_REFERENCE_TYPE = "InterPro"; // public static final String INTERPRO_ENTRY_NAME = "entry name"; // // public static final String GO_DB_REFERENCE_TYPE = "GO"; // public static final String EVIDENCE_TYPE_ATTRIBUTE = "evidence"; // // public static final String SEQUENCE_MASS_ATTRIBUTE = "mass"; // public static final String SEQUENCE_LENGTH_ATTRIBUTE = "length"; // public static final String PROTEIN_TAG_NAME = "protein"; // public static final String PROTEIN_RECOMMENDED_NAME_TAG_NAME = "recommendedName"; // public static final String PROTEIN_FULL_NAME_TAG_NAME = "fullName"; // public static final String GENE_TAG_NAME = "gene"; // public static final String GENE_NAME_TAG_NAME = "name"; // public static final String COMMENT_TAG_NAME = "comment"; // public static final String COMMENT_TYPE_ATTRIBUTE = "type"; // public static final String COMMENT_ALTERNATIVE_PRODUCTS_TYPE = "alternative products"; // public static final String COMMENT_SEQUENCE_CAUTION_TYPE = "sequence caution"; // public static final String SUBCELLULAR_LOCATION_TAG_NAME = "subcellularLocation"; // public static final String LOCATION_TAG_NAME = "location"; // public static final String COMMENT_TEXT_TAG_NAME = "text"; // public static final String FEATURE_TAG_NAME = "feature"; // public static final String FEATURE_TYPE_ATTRIBUTE = "type"; // public static final String FEATURE_DESCRIPTION_ATTRIBUTE = "description"; // public static final String STATUS_ATTRIBUTE = "status"; // public static final String FEATURE_REF_ATTRIBUTE = "ref"; // public static final String FEATURE_ID_ATTRIBUTE = "id"; // public static final String EVIDENCE_ATTRIBUTE = "evidence"; // public static final String FEATURE_LOCATION_TAG_NAME = "location"; // public static final String FEATURE_ORIGINAL_TAG_NAME = "original"; // public static final String FEATURE_VARIATION_TAG_NAME = "variation"; // public static final String FEATURE_POSITION_TAG_NAME = "position"; // public static final String FEATURE_LOCATION_BEGIN_TAG_NAME = "begin"; // public static final String FEATURE_LOCATION_END_TAG_NAME = "end"; // public static final String FEATURE_LOCATION_POSITION_ATTRIBUTE = "position"; // public static final String FEATURE_POSITION_POSITION_ATTRIBUTE = "position"; // // // } // Path: old-examples/tools/SplitUniprotXmlFile.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import com.ohnosequences.bio4j.CommonData; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.ohnosequences.bio4j.tools; /** * * @author Pablo Pareja Tobes <[email protected]> */ public class SplitUniprotXmlFile { public static void main(String[] args) { if (args.length != 2) { System.out.println("This program expects two parameters: \n" + "1. Uniprot xml input file\n" + "2. Number of entries per resulting part file\n"); } else { int numberOfEntries = Integer.parseInt(args[1]); int currentFile = 1; int currentEntry = 1; File inFile = new File(args[0]); String prefixOutFile = args[0].split("\\.")[0]; try { BufferedWriter outBuff = new BufferedWriter(new FileWriter(new File(prefixOutFile + currentFile + ".xml"))); outBuff.write("<entries>\n"); BufferedReader reader = new BufferedReader(new FileReader(inFile)); String line = null; while ((line = reader.readLine()) != null) {
if (line.trim().startsWith("<" + CommonData.ENTRY_TAG_NAME)) {
fontforge/libspiro
java/Spiro.java
// Path: java/SpiroPointType.java // public enum SpiroPointType { CORNER, G4, G2, LEFT, RIGHT, // END, OPEN, OPEN_END }
import java.lang.Math; import java.util.ArrayList; import java.io.Writer; import java.io.BufferedReader; import java.io.IOException; import static net.sourceforge.libspiro.SpiroPointType.*;
/* libspiro - conversion between spiro control points and bezier's CopySpiroPointType.RIGHT (C) 2007 Raph Levien 2009 converted to Java by George Williams This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.libspiro; public class Spiro { // Spiro has no constructors. It simply provides (static) methods to convert // between a spiro contour (an array of SpiroCP) and a cubic Bezier contour // and routines for reading/writing plate files static protected class spiro_seg { double x; double y;
// Path: java/SpiroPointType.java // public enum SpiroPointType { CORNER, G4, G2, LEFT, RIGHT, // END, OPEN, OPEN_END } // Path: java/Spiro.java import java.lang.Math; import java.util.ArrayList; import java.io.Writer; import java.io.BufferedReader; import java.io.IOException; import static net.sourceforge.libspiro.SpiroPointType.*; /* libspiro - conversion between spiro control points and bezier's CopySpiroPointType.RIGHT (C) 2007 Raph Levien 2009 converted to Java by George Williams This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.libspiro; public class Spiro { // Spiro has no constructors. It simply provides (static) methods to convert // between a spiro contour (an array of SpiroCP) and a cubic Bezier contour // and routines for reading/writing plate files static protected class spiro_seg { double x; double y;
SpiroPointType type;
fontforge/libspiro
java/SpiroCP.java
// Path: java/SpiroPointType.java // public enum SpiroPointType { CORNER, G4, G2, LEFT, RIGHT, // END, OPEN, OPEN_END }
import static net.sourceforge.libspiro.SpiroPointType.*;
/* libspiro - conversion between spiro control points and bezier's Copyright (C) 2007 Raph Levien 2009 converted to Java by George Williams This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.libspiro; public class SpiroCP { public double x,y;
// Path: java/SpiroPointType.java // public enum SpiroPointType { CORNER, G4, G2, LEFT, RIGHT, // END, OPEN, OPEN_END } // Path: java/SpiroCP.java import static net.sourceforge.libspiro.SpiroPointType.*; /* libspiro - conversion between spiro control points and bezier's Copyright (C) 2007 Raph Levien 2009 converted to Java by George Williams This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package net.sourceforge.libspiro; public class SpiroCP { public double x,y;
SpiroPointType type;
raymyers/JHaml
src/main/java/com/cadrlife/jhaml/internal/JHamlReader.java
// Path: src/main/java/com/cadrlife/jhaml/internal/org/apache/commons/io/output/NullWriter.java // public class NullWriter extends Writer { // // /** // * A singleton. // */ // public static final NullWriter NULL_WRITER = new NullWriter(); // // /** // * Constructs a new NullWriter. // */ // public NullWriter() { // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param idx The character to write // */ // public void write(int idx) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param chr The characters to write // */ // public void write(char[] chr) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param chr The characters to write // * @param st The start offset // * @param end The number of characters to write // */ // public void write(char[] chr, int st, int end) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param str The string to write // */ // public void write(String str) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param str The string to write // * @param st The start offset // * @param end The number of characters to write // */ // public void write(String str, int st, int end) { // //to /dev/null // } // // /** @see java.io.Writer#flush() */ // public void flush() { // //to /dev/null // } // // /** @see java.io.Writer#close() */ // public void close() { // //to /dev/null // } // // }
import java.io.IOException; import java.io.LineNumberReader; import com.google.common.base.CharMatcher; import com.cadrlife.jhaml.internal.org.apache.commons.io.output.NullWriter;
package com.cadrlife.jhaml.internal; public class JHamlReader { private final LineNumberReader reader; private Appendable writer; public JHamlReader(LineNumberReader reader) { this.reader = reader;
// Path: src/main/java/com/cadrlife/jhaml/internal/org/apache/commons/io/output/NullWriter.java // public class NullWriter extends Writer { // // /** // * A singleton. // */ // public static final NullWriter NULL_WRITER = new NullWriter(); // // /** // * Constructs a new NullWriter. // */ // public NullWriter() { // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param idx The character to write // */ // public void write(int idx) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param chr The characters to write // */ // public void write(char[] chr) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param chr The characters to write // * @param st The start offset // * @param end The number of characters to write // */ // public void write(char[] chr, int st, int end) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param str The string to write // */ // public void write(String str) { // //to /dev/null // } // // /** // * Does nothing - output to <code>/dev/null</code>. // * @param str The string to write // * @param st The start offset // * @param end The number of characters to write // */ // public void write(String str, int st, int end) { // //to /dev/null // } // // /** @see java.io.Writer#flush() */ // public void flush() { // //to /dev/null // } // // /** @see java.io.Writer#close() */ // public void close() { // //to /dev/null // } // // } // Path: src/main/java/com/cadrlife/jhaml/internal/JHamlReader.java import java.io.IOException; import java.io.LineNumberReader; import com.google.common.base.CharMatcher; import com.cadrlife.jhaml.internal.org.apache.commons.io.output.NullWriter; package com.cadrlife.jhaml.internal; public class JHamlReader { private final LineNumberReader reader; private Appendable writer; public JHamlReader(LineNumberReader reader) { this.reader = reader;
writer = NullWriter.NULL_WRITER;
raymyers/JHaml
src/main/java/com/cadrlife/jhaml/internal/Helper.java
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // }
import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import com.cadrlife.jhaml.JHamlConfig; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner;
package com.cadrlife.jhaml.internal; public class Helper { public static final String DOCTYPE_HTML_4_01_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"; public static final String DOCTYPE_HTML_4_01_FRAMESET = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">"; public static final String DOCTYPE_HTML_4_01_TRANSITIONAL = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; public static final String DOCTYPE_XHTML_1_0_TRANSITIONAL = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; public static final String DOCTYPE_XHTML_1_1_BASIC = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">"; public static final String DOCTYPE_XHTML_1_2_MOBILE = "<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.2//EN\" \"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd\">"; public static final String DOCTYPE_XHTML_1_0_FRAMESET = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">"; public static final String DOCTYPE_XHTML_1_0_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; public static final String DOCTYPE_HTML = "<!DOCTYPE html>"; public static final String DOCTYPE_XHTML_1_1_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">";
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // } // Path: src/main/java/com/cadrlife/jhaml/internal/Helper.java import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import com.cadrlife.jhaml.JHamlConfig; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; package com.cadrlife.jhaml.internal; public class Helper { public static final String DOCTYPE_HTML_4_01_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">"; public static final String DOCTYPE_HTML_4_01_FRAMESET = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Frameset//EN\" \"http://www.w3.org/TR/html4/frameset.dtd\">"; public static final String DOCTYPE_HTML_4_01_TRANSITIONAL = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">"; public static final String DOCTYPE_XHTML_1_0_TRANSITIONAL = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"; public static final String DOCTYPE_XHTML_1_1_BASIC = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML Basic 1.1//EN\" \"http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd\">"; public static final String DOCTYPE_XHTML_1_2_MOBILE = "<!DOCTYPE html PUBLIC \"-//WAPFORUM//DTD XHTML Mobile 1.2//EN\" \"http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd\">"; public static final String DOCTYPE_XHTML_1_0_FRAMESET = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">"; public static final String DOCTYPE_XHTML_1_0_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">"; public static final String DOCTYPE_HTML = "<!DOCTYPE html>"; public static final String DOCTYPE_XHTML_1_1_STRICT = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\" \"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">";
private final JHamlConfig config;
raymyers/JHaml
src/main/java/com/cadrlife/jhaml/JHamlConfig.java
// Path: src/main/java/com/cadrlife/jhaml/filters/CdataFilter.java // public class CdataFilter extends Filter { // // public CdataFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<![CDATA[\n" + trimEnd(indent(input,JHamlConfig.OUTPUT_INDENTATION_SIZE)) // + "\n]]>"; // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/CssFilter.java // public class CssFilter extends Filter { // // public CssFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<style type='text/css'>\n" + // "<!--\n" + // indent(trimEnd(input), JHamlConfig.OUTPUT_INDENTATION_SIZE) + "\n" + // "-->\n" + // "</style>"; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/EscapedFilter.java // public class EscapedFilter extends Filter { // // public EscapedFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return trimEnd(indent(StringEscapeUtils.escapeHtml(input),0)); // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/Filter.java // public abstract class Filter { // protected final JHamlConfig config; // // public Filter(JHamlConfig config) { // this.config = config; // } // // public abstract String process(String input); // // protected String indent(String text, int amount) { // return IndentUtils.indent(text, amount); // } // // protected String trimEnd(String string) { // return CharMatcher.WHITESPACE.trimTrailingFrom(string); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/JavaScriptFilter.java // public class JavaScriptFilter extends Filter { // // public JavaScriptFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<script type='text/javascript'>\n" + // " //<![CDATA[\n" + // indent(trimEnd(input), 4) + "\n" + // " //]]>\n" + // "</script>"; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/JspFilter.java // public class JspFilter extends Filter { // // public JspFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return new PlainFilter(config).process(input); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/MarkdownFilter.java // public class MarkdownFilter extends Filter { // // private MarkdownProcessor markdownProcessor = new MarkdownProcessor(); // // public MarkdownFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return markdownProcessor.markdown(input); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/PlainFilter.java // public class PlainFilter extends Filter { // // public PlainFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return input; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/PreserveFilter.java // public class PreserveFilter extends Filter { // // public PreserveFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // String normalizedInput = trimEnd(indent(input,-JHamlConfig.OUTPUT_INDENTATION_SIZE)); // return normalizedInput.replaceAll("\n", "&#x000A;"); // } // // }
import java.util.HashMap; import java.util.List; import java.util.Map; import com.cadrlife.jhaml.filters.CdataFilter; import com.cadrlife.jhaml.filters.CssFilter; import com.cadrlife.jhaml.filters.EscapedFilter; import com.cadrlife.jhaml.filters.Filter; import com.cadrlife.jhaml.filters.JavaScriptFilter; import com.cadrlife.jhaml.filters.JspFilter; import com.cadrlife.jhaml.filters.MarkdownFilter; import com.cadrlife.jhaml.filters.PlainFilter; import com.cadrlife.jhaml.filters.PreserveFilter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists;
package com.cadrlife.jhaml; public class JHamlConfig { public static final int OUTPUT_INDENTATION_SIZE = 2; public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); public String format = "xhtml"; public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); public List<String> preserve = Lists.newArrayList("textarea", "pre"); public String attrWrapper = "'";
// Path: src/main/java/com/cadrlife/jhaml/filters/CdataFilter.java // public class CdataFilter extends Filter { // // public CdataFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<![CDATA[\n" + trimEnd(indent(input,JHamlConfig.OUTPUT_INDENTATION_SIZE)) // + "\n]]>"; // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/CssFilter.java // public class CssFilter extends Filter { // // public CssFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<style type='text/css'>\n" + // "<!--\n" + // indent(trimEnd(input), JHamlConfig.OUTPUT_INDENTATION_SIZE) + "\n" + // "-->\n" + // "</style>"; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/EscapedFilter.java // public class EscapedFilter extends Filter { // // public EscapedFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return trimEnd(indent(StringEscapeUtils.escapeHtml(input),0)); // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/Filter.java // public abstract class Filter { // protected final JHamlConfig config; // // public Filter(JHamlConfig config) { // this.config = config; // } // // public abstract String process(String input); // // protected String indent(String text, int amount) { // return IndentUtils.indent(text, amount); // } // // protected String trimEnd(String string) { // return CharMatcher.WHITESPACE.trimTrailingFrom(string); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/JavaScriptFilter.java // public class JavaScriptFilter extends Filter { // // public JavaScriptFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return "<script type='text/javascript'>\n" + // " //<![CDATA[\n" + // indent(trimEnd(input), 4) + "\n" + // " //]]>\n" + // "</script>"; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/JspFilter.java // public class JspFilter extends Filter { // // public JspFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return new PlainFilter(config).process(input); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/MarkdownFilter.java // public class MarkdownFilter extends Filter { // // private MarkdownProcessor markdownProcessor = new MarkdownProcessor(); // // public MarkdownFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return markdownProcessor.markdown(input); // } // // } // // Path: src/main/java/com/cadrlife/jhaml/filters/PlainFilter.java // public class PlainFilter extends Filter { // // public PlainFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // return input; // } // } // // Path: src/main/java/com/cadrlife/jhaml/filters/PreserveFilter.java // public class PreserveFilter extends Filter { // // public PreserveFilter(JHamlConfig config) { // super(config); // } // // @Override // public String process(String input) { // String normalizedInput = trimEnd(indent(input,-JHamlConfig.OUTPUT_INDENTATION_SIZE)); // return normalizedInput.replaceAll("\n", "&#x000A;"); // } // // } // Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java import java.util.HashMap; import java.util.List; import java.util.Map; import com.cadrlife.jhaml.filters.CdataFilter; import com.cadrlife.jhaml.filters.CssFilter; import com.cadrlife.jhaml.filters.EscapedFilter; import com.cadrlife.jhaml.filters.Filter; import com.cadrlife.jhaml.filters.JavaScriptFilter; import com.cadrlife.jhaml.filters.JspFilter; import com.cadrlife.jhaml.filters.MarkdownFilter; import com.cadrlife.jhaml.filters.PlainFilter; import com.cadrlife.jhaml.filters.PreserveFilter; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; package com.cadrlife.jhaml; public class JHamlConfig { public static final int OUTPUT_INDENTATION_SIZE = 2; public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); public String format = "xhtml"; public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); public List<String> preserve = Lists.newArrayList("textarea", "pre"); public String attrWrapper = "'";
public Map<String,Filter> filters = new HashMap<String,Filter>();
raymyers/JHaml
src/main/java/com/cadrlife/jhaml/filters/MarkdownFilter.java
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // }
import com.cadrlife.jhaml.JHamlConfig; import com.petebevin.markdown.MarkdownProcessor;
package com.cadrlife.jhaml.filters; public class MarkdownFilter extends Filter { private MarkdownProcessor markdownProcessor = new MarkdownProcessor();
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // } // Path: src/main/java/com/cadrlife/jhaml/filters/MarkdownFilter.java import com.cadrlife.jhaml.JHamlConfig; import com.petebevin.markdown.MarkdownProcessor; package com.cadrlife.jhaml.filters; public class MarkdownFilter extends Filter { private MarkdownProcessor markdownProcessor = new MarkdownProcessor();
public MarkdownFilter(JHamlConfig config) {
raymyers/JHaml
src/main/java/com/cadrlife/jhaml/filters/Filter.java
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // } // // Path: src/main/java/com/cadrlife/jhaml/internal/util/IndentUtils.java // public class IndentUtils { // private static final CharMatcher INDENTATION_MATCHER = CharMatcher.anyOf("\t "); // // // public static String rebaseIndent(String text, int amount) { // // String current = spaces(baseIndentation(text)); // // String textWithoutFirstIndent = CharMatcher.is(' ').trimLeadingFrom(text); // // String target = spaces(amount); // // return target + textWithoutFirstIndent.replaceAll("\n", "\n"+target ); // // } // public static String indent(String text, int amount) { // if (amount >= 0) { // String target = spaces(amount); // return target + text.replaceAll("\n", "\n"+target).replaceAll("\n"+target+"\\z", "\n"); // } // if (text.length() < -amount || !INDENTATION_MATCHER.matchesAllOf(text.substring(0,-amount))) { // return text; // } // return text.substring(-amount).replaceAll("\n" + spaces(-amount), "\n"); // } // // public static String spaces(int spaces) { // String string = ""; // for (int i = 0; i<spaces; i++) { // string += " "; // } // return string; // } // // public static int baseIndentation(String text) { // return text.length() - INDENTATION_MATCHER.trimLeadingFrom(text).length(); // } // // public static boolean containsNesting(String text) { // return text.contains("\n" + spaces(baseIndentation(text)+1)); // } // // public static boolean hasContentOnFirstLine(String text) { // int endOfFirstLine = text.contains("\n") ? text.indexOf('\n') : text.length(); // return StringUtils.isNotBlank(text.substring(0, endOfFirstLine)); // } // // public static String describe(boolean isIndentWithTabs, int indentationSize) { // return indentationSize + (isIndentWithTabs ? " tab" : " space") + (indentationSize == 1 ? "" : "s"); // } // // public static String describe(String indentation) { // if (CharMatcher.is('\t').matchesAllOf(indentation)) { // return describe(true, indentation.length()); // } // if (CharMatcher.is(' ').matchesAllOf(indentation)) { // return describe(false, indentation.length()); // } // return "\"" + indentation.replaceAll("\t", "\\\\t")+ "\""; // } // }
import com.cadrlife.jhaml.JHamlConfig; import com.google.common.base.CharMatcher; import com.cadrlife.jhaml.internal.util.IndentUtils;
package com.cadrlife.jhaml.filters; public abstract class Filter { protected final JHamlConfig config; public Filter(JHamlConfig config) { this.config = config; } public abstract String process(String input); protected String indent(String text, int amount) {
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // } // // Path: src/main/java/com/cadrlife/jhaml/internal/util/IndentUtils.java // public class IndentUtils { // private static final CharMatcher INDENTATION_MATCHER = CharMatcher.anyOf("\t "); // // // public static String rebaseIndent(String text, int amount) { // // String current = spaces(baseIndentation(text)); // // String textWithoutFirstIndent = CharMatcher.is(' ').trimLeadingFrom(text); // // String target = spaces(amount); // // return target + textWithoutFirstIndent.replaceAll("\n", "\n"+target ); // // } // public static String indent(String text, int amount) { // if (amount >= 0) { // String target = spaces(amount); // return target + text.replaceAll("\n", "\n"+target).replaceAll("\n"+target+"\\z", "\n"); // } // if (text.length() < -amount || !INDENTATION_MATCHER.matchesAllOf(text.substring(0,-amount))) { // return text; // } // return text.substring(-amount).replaceAll("\n" + spaces(-amount), "\n"); // } // // public static String spaces(int spaces) { // String string = ""; // for (int i = 0; i<spaces; i++) { // string += " "; // } // return string; // } // // public static int baseIndentation(String text) { // return text.length() - INDENTATION_MATCHER.trimLeadingFrom(text).length(); // } // // public static boolean containsNesting(String text) { // return text.contains("\n" + spaces(baseIndentation(text)+1)); // } // // public static boolean hasContentOnFirstLine(String text) { // int endOfFirstLine = text.contains("\n") ? text.indexOf('\n') : text.length(); // return StringUtils.isNotBlank(text.substring(0, endOfFirstLine)); // } // // public static String describe(boolean isIndentWithTabs, int indentationSize) { // return indentationSize + (isIndentWithTabs ? " tab" : " space") + (indentationSize == 1 ? "" : "s"); // } // // public static String describe(String indentation) { // if (CharMatcher.is('\t').matchesAllOf(indentation)) { // return describe(true, indentation.length()); // } // if (CharMatcher.is(' ').matchesAllOf(indentation)) { // return describe(false, indentation.length()); // } // return "\"" + indentation.replaceAll("\t", "\\\\t")+ "\""; // } // } // Path: src/main/java/com/cadrlife/jhaml/filters/Filter.java import com.cadrlife.jhaml.JHamlConfig; import com.google.common.base.CharMatcher; import com.cadrlife.jhaml.internal.util.IndentUtils; package com.cadrlife.jhaml.filters; public abstract class Filter { protected final JHamlConfig config; public Filter(JHamlConfig config) { this.config = config; } public abstract String process(String input); protected String indent(String text, int amount) {
return IndentUtils.indent(text, amount);
raymyers/JHaml
src/test/java/com/cadrlife/jhaml/HtmlStyleAttributeHashTest.java
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // }
import static org.junit.Assert.*; import org.junit.Test; import com.cadrlife.jhaml.JHamlConfig;
@Test public void attributesCanContainElWhichShouldNotBeEscaped() { assertEquals("<html a='${foo(arg)}'></html>", render("%html(a=\"${foo(arg)}\")")); assertEquals("<html a='${a && b}'></html>", render("%html(a=\"${a && b}\")")); assertEquals("<html a='blah ${a && b}'></html>", render("%html(a=\"blah ${a && b}\")")); /* The code is not yet sophisticated enough to know to escape the parts outside the EL but not inside. In the meantime, just avoiding escaping entirely when an attribute value looks like it contains EL. Can do more if/when the need arises. */ // assertEquals("<html a='&amp; ${a && b}'></html>", render("%html(a=\"& ${a && b}\")")); } @Test public void bothStylesOfAttributes() { assertEquals("<html a='b' b='c'></html>", render("%html(a='b'){:b=>'c'}")); assertEquals("<html a='b' b='c'></html>", render("%html{:b=>'c'}(a='b')")); assertEquals("<html a='b' b='c'>(d='e')</html>", render("%html{:b=>'c'}(a='b')(d='e')")); assertEquals("<html a='b' b='c'>{:d=>'e'}</html>", render("%html{:b=>'c'}(a='b'){:d=>'e'}")); } @Test public void defaultToTrue() { assertEquals("<html a='a' b='b'></html>", render("%html(a b)")); assertEquals("<html a b></html>", renderWithFormat("html5", "%html(a b)")); } private String renderWithFormat(String format, String haml) {
// Path: src/main/java/com/cadrlife/jhaml/JHamlConfig.java // public class JHamlConfig { // public static final int OUTPUT_INDENTATION_SIZE = 2; // public static final ImmutableList<String> validFormats = ImmutableList.of("xhtml","html4","html5"); // public String format = "xhtml"; // public List<String> autoclose = Lists.newArrayList("meta", "img", "link", "br", "hr", "input", "area", "param", "col", "base"); // public List<String> preserve = Lists.newArrayList("textarea", "pre"); // public String attrWrapper = "'"; // // public Map<String,Filter> filters = new HashMap<String,Filter>(); // { // filters.put("plain", new PlainFilter(this)); // filters.put("javascript", new JavaScriptFilter(this)); // filters.put("cdata", new CdataFilter(this)); // filters.put("escaped", new EscapedFilter(this)); // filters.put("preserve", new PreserveFilter(this)); // filters.put("jsp", new JspFilter(this)); // filters.put("css", new CssFilter(this)); // filters.put("markdown", new MarkdownFilter(this)); // } // // public boolean isXhtml() { // return !isHtml(); // } // public boolean isHtml() { // return isHtml4() || isHtml5(); // } // public boolean isHtml4() { // return "html4".equals(this.format); // } // public boolean isHtml5() { // return "html5".equals(this.format); // } // // // These options escapeHtml, suppressEval, and encoding may not be necessary. // // boolean escapeHtml = false; // // boolean suppressEval = false; // // String encoding = "utf-8"; // } // Path: src/test/java/com/cadrlife/jhaml/HtmlStyleAttributeHashTest.java import static org.junit.Assert.*; import org.junit.Test; import com.cadrlife.jhaml.JHamlConfig; @Test public void attributesCanContainElWhichShouldNotBeEscaped() { assertEquals("<html a='${foo(arg)}'></html>", render("%html(a=\"${foo(arg)}\")")); assertEquals("<html a='${a && b}'></html>", render("%html(a=\"${a && b}\")")); assertEquals("<html a='blah ${a && b}'></html>", render("%html(a=\"blah ${a && b}\")")); /* The code is not yet sophisticated enough to know to escape the parts outside the EL but not inside. In the meantime, just avoiding escaping entirely when an attribute value looks like it contains EL. Can do more if/when the need arises. */ // assertEquals("<html a='&amp; ${a && b}'></html>", render("%html(a=\"& ${a && b}\")")); } @Test public void bothStylesOfAttributes() { assertEquals("<html a='b' b='c'></html>", render("%html(a='b'){:b=>'c'}")); assertEquals("<html a='b' b='c'></html>", render("%html{:b=>'c'}(a='b')")); assertEquals("<html a='b' b='c'>(d='e')</html>", render("%html{:b=>'c'}(a='b')(d='e')")); assertEquals("<html a='b' b='c'>{:d=>'e'}</html>", render("%html{:b=>'c'}(a='b'){:d=>'e'}")); } @Test public void defaultToTrue() { assertEquals("<html a='a' b='b'></html>", render("%html(a b)")); assertEquals("<html a b></html>", renderWithFormat("html5", "%html(a b)")); } private String renderWithFormat(String format, String haml) {
JHamlConfig config = new JHamlConfig();
androidthings/contrib-drivers
vcnl4200/src/test/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200Test.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: vcnl4200/src/main/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200.java // public static class InterruptStatus { // public final boolean FLAG_PS_UPFLAG; // public final boolean FLAG_PS_SPFLAG; // public final boolean FLAG_ALS_IF_L; // public final boolean FLAG_ALS_IF_H; // public final boolean FLAG_PS_IF_CLOSE; // public final boolean FLAG_PS_IF_AWAY; // // private InterruptStatus(short status) { // status = (short)((status >> 8) & 0xFF); // FLAG_PS_IF_AWAY = isBitSet(status, 0); // FLAG_PS_IF_CLOSE = isBitSet(status, 1); // FLAG_ALS_IF_H = isBitSet(status, 4); // FLAG_ALS_IF_L = isBitSet(status, 5); // FLAG_PS_SPFLAG = isBitSet(status, 6); // FLAG_PS_UPFLAG = isBitSet(status, 7); // } // // private boolean isBitSet(short word, int bitIndex) { // return ((word >> bitIndex) & 1) != 0; // } // // static InterruptStatus fromStatus(short status) { // return new InterruptStatus(status); // } // }
import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.shortThat; import static org.mockito.Mockito.times; import com.google.android.things.contrib.driver.vcnl4200.Vcnl4200.InterruptStatus; import com.google.android.things.pio.I2cDevice; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;
} @Test public void getInterruptStatus() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); vcnl4200.getInterruptStatus(); Mockito.verify(mI2c).readRegWord(eq(Vcnl4200.REGISTER_INTERRUPT_FLAGS)); } @Test public void getInterruptStatus_throwsIfClosed() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); vcnl4200.close(); mExpectedException.expect(IllegalStateException.class); vcnl4200.getInterruptStatus(); } @Test public void validateInterruptStatus() throws IOException { /** * Interrupt Status Register, High Byte (details from documentation): * 7 | PS_UPFLAG PS code saturation flag * 6 | PS_SPFLAG PS enter sunlight protection flag * 5 | ALS_IF_L, ALS crossing low THD INT trigger event * 4 | ALS_IF_H, ALS crossing high THD INT trigger event * 3 | Default = 0, reserved * 2 | Default = 0, reserved * 1 | PS_IF_CLOSE, PS rise above PS_THDH INT trigger event * 0 | PS_IF_AWAY, PS drop below PS_THDL INT trigger event */
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: vcnl4200/src/main/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200.java // public static class InterruptStatus { // public final boolean FLAG_PS_UPFLAG; // public final boolean FLAG_PS_SPFLAG; // public final boolean FLAG_ALS_IF_L; // public final boolean FLAG_ALS_IF_H; // public final boolean FLAG_PS_IF_CLOSE; // public final boolean FLAG_PS_IF_AWAY; // // private InterruptStatus(short status) { // status = (short)((status >> 8) & 0xFF); // FLAG_PS_IF_AWAY = isBitSet(status, 0); // FLAG_PS_IF_CLOSE = isBitSet(status, 1); // FLAG_ALS_IF_H = isBitSet(status, 4); // FLAG_ALS_IF_L = isBitSet(status, 5); // FLAG_PS_SPFLAG = isBitSet(status, 6); // FLAG_PS_UPFLAG = isBitSet(status, 7); // } // // private boolean isBitSet(short word, int bitIndex) { // return ((word >> bitIndex) & 1) != 0; // } // // static InterruptStatus fromStatus(short status) { // return new InterruptStatus(status); // } // } // Path: vcnl4200/src/test/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200Test.java import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.shortThat; import static org.mockito.Mockito.times; import com.google.android.things.contrib.driver.vcnl4200.Vcnl4200.InterruptStatus; import com.google.android.things.pio.I2cDevice; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; } @Test public void getInterruptStatus() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); vcnl4200.getInterruptStatus(); Mockito.verify(mI2c).readRegWord(eq(Vcnl4200.REGISTER_INTERRUPT_FLAGS)); } @Test public void getInterruptStatus_throwsIfClosed() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); vcnl4200.close(); mExpectedException.expect(IllegalStateException.class); vcnl4200.getInterruptStatus(); } @Test public void validateInterruptStatus() throws IOException { /** * Interrupt Status Register, High Byte (details from documentation): * 7 | PS_UPFLAG PS code saturation flag * 6 | PS_SPFLAG PS enter sunlight protection flag * 5 | ALS_IF_L, ALS crossing low THD INT trigger event * 4 | ALS_IF_H, ALS crossing high THD INT trigger event * 3 | Default = 0, reserved * 2 | Default = 0, reserved * 1 | PS_IF_CLOSE, PS rise above PS_THDH INT trigger event * 0 | PS_IF_AWAY, PS drop below PS_THDL INT trigger event */
InterruptStatus interruptStatus = InterruptStatus.fromStatus((short) (0b10100010 << 8));
androidthings/contrib-drivers
vcnl4200/src/test/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200Test.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: vcnl4200/src/main/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200.java // public static class InterruptStatus { // public final boolean FLAG_PS_UPFLAG; // public final boolean FLAG_PS_SPFLAG; // public final boolean FLAG_ALS_IF_L; // public final boolean FLAG_ALS_IF_H; // public final boolean FLAG_PS_IF_CLOSE; // public final boolean FLAG_PS_IF_AWAY; // // private InterruptStatus(short status) { // status = (short)((status >> 8) & 0xFF); // FLAG_PS_IF_AWAY = isBitSet(status, 0); // FLAG_PS_IF_CLOSE = isBitSet(status, 1); // FLAG_ALS_IF_H = isBitSet(status, 4); // FLAG_ALS_IF_L = isBitSet(status, 5); // FLAG_PS_SPFLAG = isBitSet(status, 6); // FLAG_PS_UPFLAG = isBitSet(status, 7); // } // // private boolean isBitSet(short word, int bitIndex) { // return ((word >> bitIndex) & 1) != 0; // } // // static InterruptStatus fromStatus(short status) { // return new InterruptStatus(status); // } // }
import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.shortThat; import static org.mockito.Mockito.times; import com.google.android.things.contrib.driver.vcnl4200.Vcnl4200.InterruptStatus; import com.google.android.things.pio.I2cDevice; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;
@Test public void validateInterruptStatus() throws IOException { /** * Interrupt Status Register, High Byte (details from documentation): * 7 | PS_UPFLAG PS code saturation flag * 6 | PS_SPFLAG PS enter sunlight protection flag * 5 | ALS_IF_L, ALS crossing low THD INT trigger event * 4 | ALS_IF_H, ALS crossing high THD INT trigger event * 3 | Default = 0, reserved * 2 | Default = 0, reserved * 1 | PS_IF_CLOSE, PS rise above PS_THDH INT trigger event * 0 | PS_IF_AWAY, PS drop below PS_THDL INT trigger event */ InterruptStatus interruptStatus = InterruptStatus.fromStatus((short) (0b10100010 << 8)); assertTrue(interruptStatus.FLAG_PS_UPFLAG); assertFalse(interruptStatus.FLAG_PS_SPFLAG); assertTrue(interruptStatus.FLAG_ALS_IF_L); assertFalse(interruptStatus.FLAG_ALS_IF_H); assertTrue(interruptStatus.FLAG_PS_IF_CLOSE); assertFalse(interruptStatus.FLAG_PS_IF_AWAY); } @Test public void setAlsIntegrationTime() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); Mockito.reset(mI2c); vcnl4200.setAlsIntegrationTime(Vcnl4200.ALS_IT_TIME_50MS); Mockito.verify(mI2c).writeRegWord(eq(Vcnl4200.REGISTER_ALS_CONF),
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: vcnl4200/src/main/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200.java // public static class InterruptStatus { // public final boolean FLAG_PS_UPFLAG; // public final boolean FLAG_PS_SPFLAG; // public final boolean FLAG_ALS_IF_L; // public final boolean FLAG_ALS_IF_H; // public final boolean FLAG_PS_IF_CLOSE; // public final boolean FLAG_PS_IF_AWAY; // // private InterruptStatus(short status) { // status = (short)((status >> 8) & 0xFF); // FLAG_PS_IF_AWAY = isBitSet(status, 0); // FLAG_PS_IF_CLOSE = isBitSet(status, 1); // FLAG_ALS_IF_H = isBitSet(status, 4); // FLAG_ALS_IF_L = isBitSet(status, 5); // FLAG_PS_SPFLAG = isBitSet(status, 6); // FLAG_PS_UPFLAG = isBitSet(status, 7); // } // // private boolean isBitSet(short word, int bitIndex) { // return ((word >> bitIndex) & 1) != 0; // } // // static InterruptStatus fromStatus(short status) { // return new InterruptStatus(status); // } // } // Path: vcnl4200/src/test/java/com/google/android/things/contrib/driver/vcnl4200/Vcnl4200Test.java import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.MockitoRule; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.shortThat; import static org.mockito.Mockito.times; import com.google.android.things.contrib.driver.vcnl4200.Vcnl4200.InterruptStatus; import com.google.android.things.pio.I2cDevice; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @Test public void validateInterruptStatus() throws IOException { /** * Interrupt Status Register, High Byte (details from documentation): * 7 | PS_UPFLAG PS code saturation flag * 6 | PS_SPFLAG PS enter sunlight protection flag * 5 | ALS_IF_L, ALS crossing low THD INT trigger event * 4 | ALS_IF_H, ALS crossing high THD INT trigger event * 3 | Default = 0, reserved * 2 | Default = 0, reserved * 1 | PS_IF_CLOSE, PS rise above PS_THDH INT trigger event * 0 | PS_IF_AWAY, PS drop below PS_THDL INT trigger event */ InterruptStatus interruptStatus = InterruptStatus.fromStatus((short) (0b10100010 << 8)); assertTrue(interruptStatus.FLAG_PS_UPFLAG); assertFalse(interruptStatus.FLAG_PS_SPFLAG); assertTrue(interruptStatus.FLAG_ALS_IF_L); assertFalse(interruptStatus.FLAG_ALS_IF_H); assertTrue(interruptStatus.FLAG_PS_IF_CLOSE); assertFalse(interruptStatus.FLAG_PS_IF_AWAY); } @Test public void setAlsIntegrationTime() throws IOException { Vcnl4200 vcnl4200 = new Vcnl4200(mI2c); Mockito.reset(mI2c); vcnl4200.setAlsIntegrationTime(Vcnl4200.ALS_IT_TIME_50MS); Mockito.verify(mI2c).writeRegWord(eq(Vcnl4200.REGISTER_ALS_CONF),
shortThat(hasBitsSet((short) Vcnl4200.ALS_IT_TIME_50MS)));
androidthings/contrib-drivers
cap1xxx/src/androidTest/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTestActivity.java
// Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // }
import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import android.app.Activity; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.util.Log; import android.view.KeyEvent; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.pio.I2cDevice; import org.mockito.Mockito;
package com.google.android.things.contrib.driver.cap12xx;/* * Copyright 2017 Google Inc. * * 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. */ public class Cap12xxTestActivity extends Activity { private static final String TAG = "Cap1xxxTestActivity";
// Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // Path: cap1xxx/src/androidTest/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTestActivity.java import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import android.app.Activity; import android.os.Bundle; import android.support.annotation.VisibleForTesting; import android.util.Log; import android.view.KeyEvent; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.pio.I2cDevice; import org.mockito.Mockito; package com.google.android.things.contrib.driver.cap12xx;/* * Copyright 2017 Google Inc. * * 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. */ public class Cap12xxTestActivity extends Activity { private static final String TAG = "Cap1xxxTestActivity";
static final Configuration CONFIGURATION = Configuration.CAP1208;
androidthings/contrib-drivers
matrixkeypad/src/main/java/com/google/android/things/contrib/driver/matrixkeypad/MatrixKeypadInputDriver.java
// Path: matrixkeypad/src/main/java/com/google/android/things/contrib/driver/matrixkeypad/MatrixKeypad.java // public interface OnKeyEventListener { // void onKeyEvent(MatrixKey matrixKey); // }
import android.os.Handler; import android.view.InputDevice; import android.view.KeyEvent; import com.google.android.things.contrib.driver.matrixkeypad.MatrixKeypad.OnKeyEventListener; import com.google.android.things.pio.Gpio; import com.google.android.things.userdriver.input.InputDriver; import com.google.android.things.userdriver.UserDriverManager; import com.google.android.things.userdriver.input.InputDriverEvent; import java.io.IOException;
/* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.matrixkeypad; /** * Driver class for a {@link MatrixKeypad} which registers an {@link InputDriver} to send key events * to the system. */ public class MatrixKeypadInputDriver implements AutoCloseable { private static final String DEVICE_NAME = "Matrix Keypad"; private MatrixKeypad mMatrixKeypad; private InputDriver mInputDriver; private int[] mKeyCodes; private InputDriverEvent mInputEvent = new InputDriverEvent();
// Path: matrixkeypad/src/main/java/com/google/android/things/contrib/driver/matrixkeypad/MatrixKeypad.java // public interface OnKeyEventListener { // void onKeyEvent(MatrixKey matrixKey); // } // Path: matrixkeypad/src/main/java/com/google/android/things/contrib/driver/matrixkeypad/MatrixKeypadInputDriver.java import android.os.Handler; import android.view.InputDevice; import android.view.KeyEvent; import com.google.android.things.contrib.driver.matrixkeypad.MatrixKeypad.OnKeyEventListener; import com.google.android.things.pio.Gpio; import com.google.android.things.userdriver.input.InputDriver; import com.google.android.things.userdriver.UserDriverManager; import com.google.android.things.userdriver.input.InputDriverEvent; import java.io.IOException; /* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.matrixkeypad; /** * Driver class for a {@link MatrixKeypad} which registers an {@link InputDriver} to send key events * to the system. */ public class MatrixKeypadInputDriver implements AutoCloseable { private static final String DEVICE_NAME = "Matrix Keypad"; private MatrixKeypad mMatrixKeypad; private InputDriver mInputDriver; private int[] mKeyCodes; private InputDriverEvent mInputEvent = new InputDriverEvent();
private OnKeyEventListener mMatrixKeyCallback = new OnKeyEventListener() {
androidthings/contrib-drivers
cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // }
import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
/* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; @RunWith(PowerMockRunner.class) @PrepareForTest({Cap1xxx.class, Gpio.class}) public class Cap1xxxTest { @Mock I2cDevice mI2c; @Mock Gpio mGpio; @Mock
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // } // Path: cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; /* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; @RunWith(PowerMockRunner.class) @PrepareForTest({Cap1xxx.class, Gpio.class}) public class Cap1xxxTest { @Mock I2cDevice mI2c; @Mock Gpio mGpio; @Mock
AlertCallback mGpioCallback;
androidthings/contrib-drivers
cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // }
import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
/* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; @RunWith(PowerMockRunner.class) @PrepareForTest({Cap1xxx.class, Gpio.class}) public class Cap1xxxTest { @Mock I2cDevice mI2c; @Mock Gpio mGpio; @Mock AlertCallback mGpioCallback; @Rule public ExpectedException mExpectedException = ExpectedException.none(); // Configuration used for all tests
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // } // Path: cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; /* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; @RunWith(PowerMockRunner.class) @PrepareForTest({Cap1xxx.class, Gpio.class}) public class Cap1xxxTest { @Mock I2cDevice mI2c; @Mock Gpio mGpio; @Mock AlertCallback mGpioCallback; @Rule public ExpectedException mExpectedException = ExpectedException.none(); // Configuration used for all tests
private static final Configuration CONFIGURATION = Configuration.CAP1188;
androidthings/contrib-drivers
cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // }
import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
private Cap1xxx mDriver; @Before public void setup() throws Exception { mGpio = PowerMockito.mock(Gpio.class); mGpioCallback = PowerMockito.mock(AlertCallback.class); PowerMockito.doNothing().when(mGpio).registerGpioCallback(any(GpioCallback.class)); PowerMockito.whenNew(AlertCallback.class).withNoArguments().thenReturn(mGpioCallback); mDriver = new Cap1xxx(mI2c, mGpio, CONFIGURATION); // clear invocations from driver init Mockito.reset(mGpio); Mockito.reset(mI2c); } @Test public void driverInit() throws IOException { // re-initialize since we want to verify invocations from driver init mDriver = new Cap1xxx(mI2c, mGpio, CONFIGURATION); verify(mGpio).setDirection(Gpio.DIRECTION_IN); verify(mGpio).setEdgeTriggerType(Gpio.EDGE_FALLING); verify(mGpio).registerGpioCallback(any(Handler.class), any(GpioCallback.class)); // setInputsEnabled verify(mI2c).writeRegByte(0x21, (byte) 0xFF); // setInterruptsEnabled verify(mI2c).writeRegByte(0x27, (byte) 0xFF); // setMultitouchInputMax verify(mI2c).writeRegByte(eq(0x2A),
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // } // Path: cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; private Cap1xxx mDriver; @Before public void setup() throws Exception { mGpio = PowerMockito.mock(Gpio.class); mGpioCallback = PowerMockito.mock(AlertCallback.class); PowerMockito.doNothing().when(mGpio).registerGpioCallback(any(GpioCallback.class)); PowerMockito.whenNew(AlertCallback.class).withNoArguments().thenReturn(mGpioCallback); mDriver = new Cap1xxx(mI2c, mGpio, CONFIGURATION); // clear invocations from driver init Mockito.reset(mGpio); Mockito.reset(mI2c); } @Test public void driverInit() throws IOException { // re-initialize since we want to verify invocations from driver init mDriver = new Cap1xxx(mI2c, mGpio, CONFIGURATION); verify(mGpio).setDirection(Gpio.DIRECTION_IN); verify(mGpio).setEdgeTriggerType(Gpio.EDGE_FALLING); verify(mGpio).registerGpioCallback(any(Handler.class), any(GpioCallback.class)); // setInputsEnabled verify(mI2c).writeRegByte(0x21, (byte) 0xFF); // setInterruptsEnabled verify(mI2c).writeRegByte(0x27, (byte) 0xFF); // setMultitouchInputMax verify(mI2c).writeRegByte(eq(0x2A),
byteThat(hasBitsSet((byte) 0b10001100)));
androidthings/contrib-drivers
cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // }
import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
// setLedBrightness Mockito.verify(mI2c).writeRegByte(0x93, (byte) 0xF0); // setLedInputLinkEnabled Mockito.verify(mI2c).writeRegByte(0x72, (byte) 0x00); // Turn off LEDs. Mockito.verify(mI2c).writeRegByte(0x74, (byte) 0x00); assertEquals(CONFIGURATION.channelCount, mDriver.getInputChannelCount()); assertEquals(CONFIGURATION.maxTouch, mDriver.getMaximumTouchPoints()); } @Test public void close() throws IOException { mDriver.close(); verify(mI2c).close(); verify(mGpio).close(); } @Test public void close_safeToCallTwice() throws IOException { mDriver.close(); mDriver.close(); verify(mI2c, times(1)).close(); verify(mGpio, times(1)).close(); } @Test public void clearInterruptFlag() throws IOException { mDriver.clearInterruptFlag(); verify(mI2c).readRegByte(0x00);
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // } // Path: cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; // setLedBrightness Mockito.verify(mI2c).writeRegByte(0x93, (byte) 0xF0); // setLedInputLinkEnabled Mockito.verify(mI2c).writeRegByte(0x72, (byte) 0x00); // Turn off LEDs. Mockito.verify(mI2c).writeRegByte(0x74, (byte) 0x00); assertEquals(CONFIGURATION.channelCount, mDriver.getInputChannelCount()); assertEquals(CONFIGURATION.maxTouch, mDriver.getMaximumTouchPoints()); } @Test public void close() throws IOException { mDriver.close(); verify(mI2c).close(); verify(mGpio).close(); } @Test public void close_safeToCallTwice() throws IOException { mDriver.close(); mDriver.close(); verify(mI2c, times(1)).close(); verify(mGpio, times(1)).close(); } @Test public void clearInterruptFlag() throws IOException { mDriver.clearInterruptFlag(); verify(mI2c).readRegByte(0x00);
verify(mI2c).writeRegByte(eq(0x00), byteThat(hasBitsNotSet((byte) 0b11111110)));
androidthings/contrib-drivers
cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // }
import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException;
} @Test public void setLedBrightness_throwsIfTooLarge() throws IOException { mExpectedException.expect(IllegalArgumentException.class); mDriver.setLedBrightness(1.1f); } @Test public void setOnCapTouchListener() throws IOException { // Setup expected values final boolean[] expectedStatus = new boolean[CONFIGURATION.channelCount]; int activeChannels = 0; // alternating true/false values for (int i = 0; i < expectedStatus.length; i += 2) { expectedStatus[i] = true; activeChannels |= (1 << i); } // Stub I2cDevice Mockito.when(mI2c.readRegByte(0x03)).thenReturn((byte) activeChannels); Mockito.when(mI2c.readRegByte(0x00)).thenReturn((byte) 0b00000001); // interrupt // Make input deltas exceed threshold readings Mockito.doAnswer(new ArrayFillingAnswer((byte) 10)) // input deltas .when(mI2c) .readRegBuffer(eq(0x10), any(byte[].class), eq(CONFIGURATION.channelCount)); Mockito.doAnswer(new ArrayFillingAnswer((byte) 5)) // input thresholds .when(mI2c) .readRegBuffer(eq(0x30), any(byte[].class), eq(CONFIGURATION.channelCount)); // Add a listener
// Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsNotSet(byte mask) { // return new BitsMatcher<>(mask, true); // } // // Path: testingutils/src/main/java/com/google/android/things/contrib/driver/testutils/BitsMatcher.java // public static BitsMatcher<Byte> hasBitsSet(byte mask) { // return new BitsMatcher<>(mask, false); // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // @VisibleForTesting // /*package*/ class AlertCallback implements GpioCallback { // @Override // public boolean onGpioEdge(Gpio gpio) { // handleInterrupt(); // return true; // } // // @Override // public void onGpioError(Gpio gpio, int error) { // Log.w(TAG, "Error handling GPIO interrupt: " + error); // } // }; // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public interface OnCapTouchListener { // /** // * Called when a touch event occurs on any of the // * controller's input channels. // * // * @param controller the touch controller triggering the event // * @param inputStatus array of input states. An input will report // * true when touched, false otherwise // */ // void onCapTouchEvent(Cap1xxx controller, boolean[] inputStatus); // } // Path: cap1xxx/src/test/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxTest.java import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsNotSet; import static com.google.android.things.contrib.driver.testutils.BitsMatcher.hasBitsSet; import static junit.framework.Assert.assertEquals; import static org.mockito.AdditionalMatchers.aryEq; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyByte; import static org.mockito.Matchers.byteThat; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import android.os.Handler; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.AlertCallback; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.OnCapTouchListener; import com.google.android.things.pio.Gpio; import com.google.android.things.pio.GpioCallback; import com.google.android.things.pio.I2cDevice; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import java.io.IOException; } @Test public void setLedBrightness_throwsIfTooLarge() throws IOException { mExpectedException.expect(IllegalArgumentException.class); mDriver.setLedBrightness(1.1f); } @Test public void setOnCapTouchListener() throws IOException { // Setup expected values final boolean[] expectedStatus = new boolean[CONFIGURATION.channelCount]; int activeChannels = 0; // alternating true/false values for (int i = 0; i < expectedStatus.length; i += 2) { expectedStatus[i] = true; activeChannels |= (1 << i); } // Stub I2cDevice Mockito.when(mI2c.readRegByte(0x03)).thenReturn((byte) activeChannels); Mockito.when(mI2c.readRegByte(0x00)).thenReturn((byte) 0b00000001); // interrupt // Make input deltas exceed threshold readings Mockito.doAnswer(new ArrayFillingAnswer((byte) 10)) // input deltas .when(mI2c) .readRegBuffer(eq(0x10), any(byte[].class), eq(CONFIGURATION.channelCount)); Mockito.doAnswer(new ArrayFillingAnswer((byte) 5)) // input thresholds .when(mI2c) .readRegBuffer(eq(0x30), any(byte[].class), eq(CONFIGURATION.channelCount)); // Add a listener
OnCapTouchListener mockListener = Mockito.mock(OnCapTouchListener.class);
androidthings/contrib-drivers
cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxInputDriver.java
// Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // }
import android.content.Context; import android.os.Handler; import android.support.annotation.VisibleForTesting; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.userdriver.input.InputDriver; import com.google.android.things.userdriver.UserDriverManager; import com.google.android.things.userdriver.input.InputDriverEvent; import java.io.IOException;
/* * Copyright 2016 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; /** * User-space driver to process capacitive touch events from the * CAP1xxx family of touch controllers and forward them to the * Android input framework. */ @SuppressWarnings("WeakerAccess") public class Cap1xxxInputDriver implements AutoCloseable { private static final String TAG = "Cap1xxxInputDriver"; // Driver parameters private static final String DRIVER_NAME = "Cap1xxx"; private Cap1xxx mPeripheralDevice; // Framework input driver private InputDriver mInputDriver; // Key codes mapped to input channels private int[] mKeycodes; /** * @deprecated Use {@link #Cap1xxxInputDriver(String, String, Configuration, int[])} instead. */ @Deprecated
// Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxx.java // public enum Configuration { // // Channel Count, Max Touch Inputs, LED Count // CAP1203(3,3,0), // CAP1293(3,3,0), // CAP1206(6,4,0), // CAP1296(6,4,0), // CAP1208(8,4,0), // CAP1298(8,4,0), // CAP1105(5,3,0), // CAP1106(6,4,0), // CAP1126(6,4,2), // CAP1128(8,4,2), // CAP1133(3,3,3), // CAP1166(6,4,6), // CAP1188(8,4,8); // // final int channelCount; // final int maxTouch; // final int ledCount; // Configuration(int channelCount, int maxTouch, int ledCount) { // this.channelCount = channelCount; // this.maxTouch = maxTouch; // this.ledCount = ledCount; // } // } // Path: cap1xxx/src/main/java/com/google/android/things/contrib/driver/cap1xxx/Cap1xxxInputDriver.java import android.content.Context; import android.os.Handler; import android.support.annotation.VisibleForTesting; import android.util.Log; import android.view.InputDevice; import android.view.KeyEvent; import com.google.android.things.contrib.driver.cap1xxx.Cap1xxx.Configuration; import com.google.android.things.userdriver.input.InputDriver; import com.google.android.things.userdriver.UserDriverManager; import com.google.android.things.userdriver.input.InputDriverEvent; import java.io.IOException; /* * Copyright 2016 Google Inc. * * 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.android.things.contrib.driver.cap1xxx; /** * User-space driver to process capacitive touch events from the * CAP1xxx family of touch controllers and forward them to the * Android input framework. */ @SuppressWarnings("WeakerAccess") public class Cap1xxxInputDriver implements AutoCloseable { private static final String TAG = "Cap1xxxInputDriver"; // Driver parameters private static final String DRIVER_NAME = "Cap1xxx"; private Cap1xxx mPeripheralDevice; // Framework input driver private InputDriver mInputDriver; // Key codes mapped to input channels private int[] mKeycodes; /** * @deprecated Use {@link #Cap1xxxInputDriver(String, String, Configuration, int[])} instead. */ @Deprecated
public Cap1xxxInputDriver(Context context, String i2cName, String alertName, Configuration chip,
androidthings/contrib-drivers
button/src/androidTest/java/com/google/android/things/contrib/driver/button/ButtonTestActivity.java
// Path: button/src/main/java/com/google/android/things/contrib/driver/button/Button.java // public enum LogicState { // PRESSED_WHEN_HIGH, // PRESSED_WHEN_LOW // }
import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import com.google.android.things.contrib.driver.button.Button.LogicState; import com.google.android.things.pio.Gpio; import org.mockito.Mockito; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit;
/* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.button; public class ButtonTestActivity extends Activity { private static final String TAG = "ButtonTestActivity"; public static final int KEYCODE = KeyEvent.KEYCODE_ENTER; private Gpio mGpio; private Button mButton; private ButtonInputDriver mInputDriver; private BlockingQueue<KeyEvent> mKeyDownEvents; private BlockingQueue<KeyEvent> mKeyUpEvents; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGpio = Mockito.mock(Gpio.class); try {
// Path: button/src/main/java/com/google/android/things/contrib/driver/button/Button.java // public enum LogicState { // PRESSED_WHEN_HIGH, // PRESSED_WHEN_LOW // } // Path: button/src/androidTest/java/com/google/android/things/contrib/driver/button/ButtonTestActivity.java import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import com.google.android.things.contrib.driver.button.Button.LogicState; import com.google.android.things.pio.Gpio; import org.mockito.Mockito; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /* * Copyright 2017 Google Inc. * * 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.android.things.contrib.driver.button; public class ButtonTestActivity extends Activity { private static final String TAG = "ButtonTestActivity"; public static final int KEYCODE = KeyEvent.KEYCODE_ENTER; private Gpio mGpio; private Button mButton; private ButtonInputDriver mInputDriver; private BlockingQueue<KeyEvent> mKeyDownEvents; private BlockingQueue<KeyEvent> mKeyUpEvents; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGpio = Mockito.mock(Gpio.class); try {
mButton = new Button(mGpio, LogicState.PRESSED_WHEN_HIGH);
Labs64/NetLicensingClient-java
NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/AbstractRestProvider.java
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java // public interface Authentication { // // String getUsername(); // // String getPassword(); // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/TokenAuthentication.java // public class TokenAuthentication implements Authentication { // // private final String token; // // /** // * Token auth constructor. // * // * @param token // * authentication token // */ // public TokenAuthentication(final String token) { // this.token = token; // } // // @Override // public String getUsername() { // return "apiKey"; // } // // @Override // public String getPassword() { // return token; // } // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/UsernamePasswordAuthentication.java // public class UsernamePasswordAuthentication implements Authentication { // // private final String username; // private final String password; // // /** // * Constructor // * // * @param username // * for basic HTTP authentication // * @param password // * for basic HTTP authentication // */ // public UsernamePasswordAuthentication(final String username, final String password) { // this.username = username; // this.password = password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public String getPassword() { // return password; // } // // }
import com.labs64.netlicensing.provider.auth.UsernamePasswordAuthentication; import com.labs64.netlicensing.provider.auth.Authentication; import com.labs64.netlicensing.provider.auth.TokenAuthentication;
/* 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.labs64.netlicensing.provider; /** */ public abstract class AbstractRestProvider implements RestProvider { private Authentication authentication; private RestProvider.Configuration configuration; @Override public RestProvider authenticate(final Authentication authentication) { this.authentication = authentication; return this; } @Override public RestProvider authenticate(final String username, final String password) {
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java // public interface Authentication { // // String getUsername(); // // String getPassword(); // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/TokenAuthentication.java // public class TokenAuthentication implements Authentication { // // private final String token; // // /** // * Token auth constructor. // * // * @param token // * authentication token // */ // public TokenAuthentication(final String token) { // this.token = token; // } // // @Override // public String getUsername() { // return "apiKey"; // } // // @Override // public String getPassword() { // return token; // } // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/UsernamePasswordAuthentication.java // public class UsernamePasswordAuthentication implements Authentication { // // private final String username; // private final String password; // // /** // * Constructor // * // * @param username // * for basic HTTP authentication // * @param password // * for basic HTTP authentication // */ // public UsernamePasswordAuthentication(final String username, final String password) { // this.username = username; // this.password = password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public String getPassword() { // return password; // } // // } // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/AbstractRestProvider.java import com.labs64.netlicensing.provider.auth.UsernamePasswordAuthentication; import com.labs64.netlicensing.provider.auth.Authentication; import com.labs64.netlicensing.provider.auth.TokenAuthentication; /* 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.labs64.netlicensing.provider; /** */ public abstract class AbstractRestProvider implements RestProvider { private Authentication authentication; private RestProvider.Configuration configuration; @Override public RestProvider authenticate(final Authentication authentication) { this.authentication = authentication; return this; } @Override public RestProvider authenticate(final String username, final String password) {
authentication = new UsernamePasswordAuthentication(username, password);
Labs64/NetLicensingClient-java
NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/AbstractRestProvider.java
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java // public interface Authentication { // // String getUsername(); // // String getPassword(); // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/TokenAuthentication.java // public class TokenAuthentication implements Authentication { // // private final String token; // // /** // * Token auth constructor. // * // * @param token // * authentication token // */ // public TokenAuthentication(final String token) { // this.token = token; // } // // @Override // public String getUsername() { // return "apiKey"; // } // // @Override // public String getPassword() { // return token; // } // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/UsernamePasswordAuthentication.java // public class UsernamePasswordAuthentication implements Authentication { // // private final String username; // private final String password; // // /** // * Constructor // * // * @param username // * for basic HTTP authentication // * @param password // * for basic HTTP authentication // */ // public UsernamePasswordAuthentication(final String username, final String password) { // this.username = username; // this.password = password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public String getPassword() { // return password; // } // // }
import com.labs64.netlicensing.provider.auth.UsernamePasswordAuthentication; import com.labs64.netlicensing.provider.auth.Authentication; import com.labs64.netlicensing.provider.auth.TokenAuthentication;
/* 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.labs64.netlicensing.provider; /** */ public abstract class AbstractRestProvider implements RestProvider { private Authentication authentication; private RestProvider.Configuration configuration; @Override public RestProvider authenticate(final Authentication authentication) { this.authentication = authentication; return this; } @Override public RestProvider authenticate(final String username, final String password) { authentication = new UsernamePasswordAuthentication(username, password); return this; } @Override public RestProvider authenticate(final String token) {
// Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/Authentication.java // public interface Authentication { // // String getUsername(); // // String getPassword(); // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/TokenAuthentication.java // public class TokenAuthentication implements Authentication { // // private final String token; // // /** // * Token auth constructor. // * // * @param token // * authentication token // */ // public TokenAuthentication(final String token) { // this.token = token; // } // // @Override // public String getUsername() { // return "apiKey"; // } // // @Override // public String getPassword() { // return token; // } // // } // // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/auth/UsernamePasswordAuthentication.java // public class UsernamePasswordAuthentication implements Authentication { // // private final String username; // private final String password; // // /** // * Constructor // * // * @param username // * for basic HTTP authentication // * @param password // * for basic HTTP authentication // */ // public UsernamePasswordAuthentication(final String username, final String password) { // this.username = username; // this.password = password; // } // // @Override // public String getUsername() { // return username; // } // // @Override // public String getPassword() { // return password; // } // // } // Path: NetLicensingClient/src/main/java/com/labs64/netlicensing/provider/AbstractRestProvider.java import com.labs64.netlicensing.provider.auth.UsernamePasswordAuthentication; import com.labs64.netlicensing.provider.auth.Authentication; import com.labs64.netlicensing.provider.auth.TokenAuthentication; /* 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.labs64.netlicensing.provider; /** */ public abstract class AbstractRestProvider implements RestProvider { private Authentication authentication; private RestProvider.Configuration configuration; @Override public RestProvider authenticate(final Authentication authentication) { this.authentication = authentication; return this; } @Override public RestProvider authenticate(final String username, final String password) { authentication = new UsernamePasswordAuthentication(username, password); return this; } @Override public RestProvider authenticate(final String token) {
authentication = new TokenAuthentication(token);