diff --git a/.travis.yml b/.travis.yml index b0c9864..4c17bc9 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,7 +1,6 @@ language: java jdk: - - openjdk7 - - oraclejdk7 + - oraclejdk8 script: mvn clean test \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5ce3e3e..16a0c48 100644 --- a/pom.xml +++ b/pom.xml @@ -5,15 +5,15 @@ 4.0.0 BookingBug-SDK - BookingBug-SDK - 1.9 + BookingBug-SDK2 + 2.2 - bintray-acornel-bb-java - acornel-bb-java - https://api.bintray.com/maven/acornel/bb-java/bookingbug-java/;publish=1 + bintray-bookingbug-bookingbug-java + BookingBug-bookingbug-java + https://api.bintray.com/maven/bookingbug/bookingbug-java/BookingBug-JavaSDK/;publish=1 @@ -113,16 +113,100 @@ src/test/resources + + src/main/resources + maven-compiler-plugin - 1.7 - 1.7 + 1.8 + 1.8 + 1.7 + 1.7 + + + + + maven-surefire-plugin + + + + maven-failsafe-plugin + + + + integration-test + verify + + + + + + + net.orfjackal.retrolambda + retrolambda-maven-plugin + 2.3.0 + + + + process-main + process-test + + + + + ${testBytecodeTarget} + ${testDefaultMethods} + ${testFork} + + + + + org.codehaus.mojo + animal-sniffer-maven-plugin + 1.7 + + + signature-check + verify + + check + + + + + + org.codehaus.mojo.signature + java17 + 1.0 + + + + noDefaultMethods + + false + + + + + maven-compiler-plugin + + + **/DefaultMethodsTest.java + **/InterfaceStaticMethodsTest.java + + + + + + + + \ No newline at end of file diff --git a/src/main/bookingbugAPI/api/API.java b/src/main/bookingbugAPI/api/API.java deleted file mode 100644 index 358e675..0000000 --- a/src/main/bookingbugAPI/api/API.java +++ /dev/null @@ -1,22 +0,0 @@ -package bookingbugAPI.api; - -/** - * Created by sebi on 19.05.2016. - */ -public class API extends AbstractAPI { - - public API(ApiConfig config) { - super(config); - } - - public AdminAPI admin() { - return new AdminAPI(newConfig()); - } - - public static class APIBuilder extends AbstractAPI.ApiConfig { - - public API build() { - return new API(this); - } - } -} diff --git a/src/main/bookingbugAPI/api/AbstractAPI.java b/src/main/bookingbugAPI/api/AbstractAPI.java deleted file mode 100644 index 4c7386c..0000000 --- a/src/main/bookingbugAPI/api/AbstractAPI.java +++ /dev/null @@ -1,133 +0,0 @@ -package bookingbugAPI.api; - -import bookingbugAPI.services.CacheService; -import bookingbugAPI.services.OkHttpService; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.StringReader; -import java.util.Properties; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Abstract API class - * Contains basic methods and members - */ -public abstract class AbstractAPI { - - protected OkHttpService httpService; - - public AbstractAPI(ApiConfig config){ - httpService = new OkHttpService(config); - } - - public ApiConfig newConfig() { - return new ApiConfig(httpService.getConfig()); - } - - public String getAuthToken(){ - return httpService.getConfig().auth_token; - } - - public void setAuthToken(String auth_token) { - httpService.getConfig().withAuthToken(auth_token); - } - - /** - * Class which holds an API configuration - * @param Keep fluent interface for subclasses - */ - public static class ApiConfig { - - static final String propFileName = "bb_sdk_config.properties"; - private final static Logger logger = Logger.getLogger(ApiConfig.class.getName()); - - public String auth_token; - public String appId; - public String appKey; - public String userAgent; - public String serverUrl; - public CacheService cacheService; - - public ApiConfig(ApiConfig config) { - this.auth_token = config.auth_token; - this.appId = config.appId; - this.appKey = config.appKey; - this.userAgent = config.userAgent; - this.serverUrl = config.serverUrl; - this.cacheService = config.cacheService; - } - - public ApiConfig() { - loadConfigFile(null); - cacheService = CacheService.JDBC(); - } - - public T withNothing() { - auth_token = null; - appId = ""; - appKey = ""; - userAgent = ""; - serverUrl = null; - cacheService = null; - return (T) this; - } - - public T withAuthToken(String token) { - this.auth_token = token; - return (T)this; - } - - public T withCache(CacheService cacheService) { - this.cacheService = cacheService; - return (T)this; - } - - public T withApp(String appId, String appKey) { - this.appId = appId; - this.appKey = appKey; - return (T)this; - } - - public T withUserAgent(String userAgent) { - this.userAgent = userAgent; - return (T)this; - } - - public T withServerUrl(String serverUrl) { - this.serverUrl = serverUrl; - return (T)this; - } - - public T withConfigString(String configString) { - loadConfigFile(configString); - return (T)this; - } - - private void loadConfigFile(String configString) { - try{ - Properties prop = new Properties(); - - if(configString != null) { - prop.load(new StringReader(configString)); - } - else { - InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propFileName); - if (inputStream != null) { - prop.load(inputStream); - } else { - throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); - } - } - - appId = prop.getProperty("application.auth.appid"); - appKey = prop.getProperty("application.auth.appkey"); - userAgent = prop.getProperty("application.auth.useragent"); - serverUrl = prop.getProperty("application.auth.serverurl"); - } catch (Exception e) { - logger.log(Level.SEVERE, "Exception @ ApiConfig.withConfigFile(): " + e.getMessage()); - } - } - } -} diff --git a/src/main/bookingbugAPI/api/AdminAPI.java b/src/main/bookingbugAPI/api/AdminAPI.java deleted file mode 100644 index b1872a0..0000000 --- a/src/main/bookingbugAPI/api/AdminAPI.java +++ /dev/null @@ -1,184 +0,0 @@ -package bookingbugAPI.api; - -import bookingbugAPI.models.*; -import bookingbugAPI.models.params.BookingListParams; -import bookingbugAPI.models.params.ServiceListParams; -import bookingbugAPI.services.HttpService; -import bookingbugAPI.services.OkHttpService; -import com.damnhandy.uri.template.UriTemplate; -import helpers.Utils; - -import java.io.IOException; -import java.net.URL; - - -public class AdminAPI extends AbstractAPI { - - AdminAPI(ApiConfig builder) { - super(builder); - } - - /** - * Accessor to create an instance of {@link BookingAPI} with current configuration - * @return BookingAPI instance - */ - public BookingAPI booking() { - return new BookingAPI(newConfig()); - } - - public class BookingAPI extends AbstractAPI { - - BookingAPI(ApiConfig config) { - super(config); - } - - /** - * Get a list of admin bookings for a company - * @param company The owning company for bookin - * @param bLParams The parameters for this call - * @return Collection of bookings - * @throws IOException - */ - public BBCollection bookingList(Company company, BookingListParams bLParams) throws IOException { - URL url = new URL(Utils.inflateLink(company.getBookingsLink(), bLParams.getParams())); - BBCollection bookings = new BBCollection(httpService.api_GET(url), getAuthToken(), "bookings", Booking.class); - //BBCollection bookings = new BBCollection(HttpService.api_GET(url, getAuthToken()), getAuthToken(), "bookings", Booking.class); - return bookings; - } - - /** - * Get all details about a specific booking - * @param company the company owning the booking - * @param bookingId the id of booking to read - * @return Booking - * @throws IOException - */ - public Booking bookingRead(Company company, String bookingId) throws IOException { - URL url = new URL(AdminURLS.Bookings.bookingRead() - .set("companyId", company.id) - .set("bookingId", bookingId) - .expand()); - return new Booking(httpService.api_GET(url)); - } - - /** - * Get the edit schema for booking - * @param booking - * @return SchemaForm - * @throws IOException - */ - public SchemaForm getEditBookingSchema(Booking booking) throws IOException { - URL url = new URL(UriTemplate.fromTemplate(booking.getEditLink()).expand()); - return new SchemaForm(HttpService.api_GET(url, httpService.getConfig().auth_token)); - } - } - - - /** - * Accessor to create an instance of {@link CompanyAPI} with current configuration - * @return CompanyAPI instance - */ - public CompanyAPI company() { - return new CompanyAPI(newConfig()); - } - - public class CompanyAPI extends AbstractAPI { - - public CompanyAPI(ApiConfig config) { - super(config); - } - - - /** - * Load All of the Links and Properties of a Company - * @param companyId the id of company - * @return Company - * @throws IOException - */ - public Company companyRead(String companyId) throws IOException { - URL url = new URL(AdminURLS.Company.companyRead().set("companyId", companyId).expand()); - return new Company(httpService.api_GET(url)); - } - - } - - - /** - * Accessor to create an instance of {@link ServiceAPI} with current configuration - * @return ServiceAPI instance - */ - public ServiceAPI service() { - return new ServiceAPI(newConfig()); - } - - public class ServiceAPI extends AbstractAPI { - - public ServiceAPI(ApiConfig config) { - super(config); - } - - /** - * List of Services for a company. Results are returned as a paginated list - * @param company The owning company for services - * @param slParams Parameters for this call - * @return Collection of Service - * @throws IOException - */ - public BBCollection serviceList(Company company, ServiceListParams slParams) throws IOException { - UriTemplate template = Utils.TemplateWithPagination(company.getServicesLink(), slParams); - URL url = new URL(template.expand()); - - BBCollection services = new BBCollection(httpService.api_GET(url), httpService.getConfig().auth_token, "services", Service.class); - return services; - } - - /** - * Load a Specific Service Details - * @param company The owning company for service - * @param serviceId the id of service to load - * @return Service - * @throws IOException - */ - public Service serviceRead(Company company, String serviceId) throws IOException{ - URL url = new URL(AdminURLS.Service.serviceRead() - .set("companyId", company.id) - .set("serviceId", serviceId) - .expand()); - return new Service(httpService.api_GET(url)); - } - - /** - * Get schema for creating a new service - * @param company The owning company - * @return SchemaForm - * @throws IOException - */ - public SchemaForm getNewServiceSchema(Company company) throws IOException { - URL url = new URL(UriTemplate.fromTemplate(company.getNewServiceLink()).expand()); - return new SchemaForm(HttpService.api_GET(url, httpService.getConfig().auth_token)); - } - - /** - * Get a schema for creating a new booking with provided service - * @param service The service - * @return SchemaForm - * @throws IOException - */ - public SchemaForm getNewBookingSchema(Service service) throws IOException { - URL url = new URL(UriTemplate.fromTemplate(service.get_newBookingLik()).expand()); - return new SchemaForm(HttpService.api_GET(url, httpService.getConfig().auth_token)); - } - - /** - * Get a schema for editing a service - * @param service The service to be edited - * @return SchemaForm - * @throws IOException - */ - public SchemaForm getEditServiceSchema(Service service) throws IOException { - URL url = new URL(UriTemplate.fromTemplate(service.get_editServiceLik()).expand()); - return new SchemaForm(HttpService.api_GET(url, httpService.getConfig().auth_token)); - } - } - -} diff --git a/src/main/bookingbugAPI/models/params/ClientListParams.java b/src/main/bookingbugAPI/models/params/ClientListParams.java deleted file mode 100644 index e8eb7b2..0000000 --- a/src/main/bookingbugAPI/models/params/ClientListParams.java +++ /dev/null @@ -1,118 +0,0 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; - - -public class ClientListParams { - - String page; - String per_page; - String filter_by; - String filter_by_fields; - String order_by; - String order_by_reverse; - - - public ClientListParams(){} - - - public ClientListParams(Map args){ - if (args==null || args.isEmpty()) { - return; - } - - String strValue; - - for (Map.Entry entry : args.entrySet()) { - final String[] value = entry.getValue(); - if (value[0]!=null && !value[0].trim().isEmpty()) { - strValue = null; - } else { - strValue = value[0]; - } - - switch(entry.getKey()) { - case "page": page = strValue; - break; - case "per_page": per_page = strValue; - break; - case "filter_by": filter_by = strValue; - break; - case "filter_by_fields": filter_by_fields = strValue; - break; - case "order_by": order_by = strValue; - break; - case "order_by_reverse": order_by_reverse = strValue; - break; - } - } - } - - - /** - * getParams - * @return Map - */ - public Map getParams() { - Map params = new HashMap(); - - params.put("page", new String[]{page}); - params.put("per_page", new String[]{per_page}); - params.put("filter_by", new String[]{filter_by}); - params.put("filter_by_fields", new String[]{filter_by_fields}); - params.put("order_by", new String[]{order_by}); - params.put("order_by_reverse", new String[]{order_by_reverse}); - - return params; - } - - - public String getPage() { - return page; - } - - public void setPage(String page) { - this.page = page; - } - - public String getPerPage() { - return per_page; - } - - public void setPerPage(String per_page) { - this.per_page = per_page; - } - - public String getFilterBy() { - return filter_by; - } - - public void setFilterBy(String filter_by) { - this.filter_by = filter_by; - } - - public String getFilterByFields() { - return filter_by_fields; - } - - public void setFilterByFields(String filter_by_fields) { - this.filter_by_fields = filter_by_fields; - } - - public String getOrderBy() { - return order_by; - } - - public void setOrderBy(String order_by) { - this.order_by = order_by; - } - - public String getOrderByReverse() { - return order_by_reverse; - } - - public void setOrderByReverse(String order_by_reverse) { - this.order_by_reverse = order_by_reverse; - } -} diff --git a/src/main/bookingbugAPI/models/params/PurchaseListParams.java b/src/main/bookingbugAPI/models/params/PurchaseListParams.java deleted file mode 100644 index c0c1ff6..0000000 --- a/src/main/bookingbugAPI/models/params/PurchaseListParams.java +++ /dev/null @@ -1,106 +0,0 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; - - -public class PurchaseListParams { - - String created_from; - String created_to; - String admin_bookings_only; - String order_by; - String order_by_reverse; - - - public PurchaseListParams(){} - - - public PurchaseListParams(Map args){ - if (args==null || args.isEmpty()) { - return; - } - - String strValue; - - for (Map.Entry entry : args.entrySet()) { - final String[] value = entry.getValue(); - if (value[0]!=null && !value[0].trim().isEmpty()) { - strValue = null; - } else { - strValue = value[0]; - } - - switch(entry.getKey()) { - case "created_from": created_from = strValue; - break; - case "created_to": created_to = strValue; - break; - case "admin_bookings_only": admin_bookings_only = strValue; - break; - case "order_by": order_by = strValue; - break; - case "order_by_reverse": order_by_reverse = strValue; - break; - } - } - } - - - /** - * getParams - * @return Map - */ - public Map getParams() { - Map params = new HashMap(); - - params.put("created_from", new String[]{created_from}); - params.put("created_to", new String[]{created_to}); - params.put("admin_bookings_only", new String[]{admin_bookings_only}); - params.put("order_by", new String[]{order_by}); - params.put("order_by_reverse", new String[]{order_by_reverse}); - - return params; - } - - - public String getCreated_from() { - return created_from; - } - - public void setCreated_from(String created_from) { - this.created_from = created_from; - } - - public String getCreated_to() { - return created_to; - } - - public void setCreated_to(String created_to) { - this.created_to = created_to; - } - - public String getAdmin_bookings_only() { - return admin_bookings_only; - } - - public void setAdmin_bookings_only(String admin_bookings_only) { - this.admin_bookings_only = admin_bookings_only; - } - - public String getOrder_by() { - return order_by; - } - - public void setOrder_by(String order_by) { - this.order_by = order_by; - } - - public String getOrder_by_reverse() { - return order_by_reverse; - } - - public void setOrder_by_reverse(String order_by_reverse) { - this.order_by_reverse = order_by_reverse; - } -} diff --git a/src/main/bookingbugAPI/models/params/QuestionListParams.java b/src/main/bookingbugAPI/models/params/QuestionListParams.java deleted file mode 100644 index a84a708..0000000 --- a/src/main/bookingbugAPI/models/params/QuestionListParams.java +++ /dev/null @@ -1,59 +0,0 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; - - -public class QuestionListParams { - - String detail_group_id; - - - public QuestionListParams(){} - - - public QuestionListParams(Map args){ - if (args==null || args.isEmpty()) { - return; - } - - String strValue; - - for (Map.Entry entry : args.entrySet()) { - final String[] value = entry.getValue(); - if (value[0]!=null && !value[0].trim().isEmpty()) { - strValue = null; - } else { - strValue = value[0]; - } - - switch(entry.getKey()) { - case "detail_group_id": detail_group_id = strValue; - break; - } - } - } - - - /** - * getParams - * @return Map - */ - public Map getParams() { - Map params = new HashMap(); - - params.put("detail_group_id", new String[]{detail_group_id}); - - return params; - } - - - public String getDetailGroupId() { - return detail_group_id; - } - - public void setDetailGroupId(String detail_group_id) { - this.detail_group_id = detail_group_id; - } - -} diff --git a/src/main/bookingbugAPI/services/CacheService.java b/src/main/bookingbugAPI/services/CacheService.java deleted file mode 100644 index 3f448c5..0000000 --- a/src/main/bookingbugAPI/services/CacheService.java +++ /dev/null @@ -1,107 +0,0 @@ -package bookingbugAPI.services; - -import com.j256.ormlite.dao.Dao; -import com.j256.ormlite.dao.DaoManager; -import com.j256.ormlite.jdbc.JdbcConnectionSource; -import com.j256.ormlite.stmt.QueryBuilder; -import com.j256.ormlite.support.ConnectionSource; -import com.j256.ormlite.table.TableUtils; - -import java.sql.SQLException; -import java.util.List; - -/** - * Class used for caching HTTP Responses - */ -public class CacheService { - - SQLite db; - boolean mock; - - public CacheService(SQLite db, boolean mock) { - this.db = db; - this.mock = mock; - } - - public static CacheService JDBC() { - return new CacheService(new JDBC_Sqlite(), false); - } - - public static CacheService MOCK() { - return new CacheService(new JDBC_Sqlite(), true); - } - - public void storeResult(String url, String method, String resp) { - if(mock) return; - - Dao respDao; - - try { - db.createIfNotExists(); - respDao = db.getDao(); - - HttpService.NetResponse response = new HttpService.NetResponse(url, method, resp); - respDao.create(response); - - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public HttpService.NetResponse getDBResponse(String url, String method) { - if(mock) return null; - try { - db.createIfNotExists(); - Dao respDao = db.getDao(); - QueryBuilder builder = respDao.queryBuilder(); - builder.where().eq("url", url).and().eq("method", method); - List responses = respDao.query(builder.prepare()); - if(responses.size() > 0) - return responses.get(0); - - } catch (SQLException e) { - e.printStackTrace(); - } - return null; - } - - - /** - * Classes should implement this interface to provide proper handling for SQLite db - */ - public interface SQLite { - - Dao getDao() throws SQLException; - ConnectionSource getConnectionSource() throws SQLException; - void createIfNotExists() throws SQLException; - - } - - /** - * Implementation for SQLite with JDBC - */ - public static final class JDBC_Sqlite implements SQLite { - - ConnectionSource connectionSource; - Dao dao; - - @Override - public void createIfNotExists() throws SQLException { - TableUtils.createTableIfNotExists(getConnectionSource(), HttpService.NetResponse.class); - } - - @Override - public Dao getDao() throws SQLException { - if(dao == null) - dao = DaoManager.createDao(getConnectionSource(), HttpService.NetResponse.class); - return dao; - } - - @Override - public ConnectionSource getConnectionSource() throws SQLException { - if(connectionSource == null) - connectionSource = new JdbcConnectionSource("jdbc:sqlite:test.db"); - return connectionSource; - } - } -} diff --git a/src/main/bookingbugAPI/services/OkHttpService.java b/src/main/bookingbugAPI/services/OkHttpService.java deleted file mode 100644 index 8a7f9da..0000000 --- a/src/main/bookingbugAPI/services/OkHttpService.java +++ /dev/null @@ -1,200 +0,0 @@ -package bookingbugAPI.services; - -import bookingbugAPI.api.AbstractAPI; -import bookingbugAPI.models.HttpException; -import helpers.Http; -import helpers.HttpServiceResponse; -import helpers.Utils; -import okhttp3.*; - -import java.io.IOException; -import java.net.URL; -import java.util.Map; -import java.util.Objects; - - -/** - * Created by sebi on 23.05.2016. - */ -public class OkHttpService { - - AbstractAPI.ApiConfig config; - private final OkHttpClient client = new OkHttpClient(); - - public OkHttpService(AbstractAPI.ApiConfig config) { - this.config = config; - } - - /** - * Get current service configuration - * @return {@link bookingbugAPI.api.AbstractAPI.ApiConfig} - */ - public AbstractAPI.ApiConfig getConfig() { - return config; - } - - - /** - * Makes a synchronous GET request - * @param url URL to get - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_GET(URL url) throws HttpException { - return callApi(url, "GET", HttpService.urlEncodedContentType, null); - } - - - /** - * Makes a synchronous POST request with {@link Http#urlEncodedContentType} contentType - * @param url URL to post to - * @param params Map, a generic Map containing data to post - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_POST(URL url, Map params) throws HttpException { - return callApi(url, "POST", HttpService.urlEncodedContentType, params); - } - - - /** - * Makes a synchronous POST request with specific contentType - * @param url URL to post to - * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. - * @param params Map, a generic Map containing data to post - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_POST(URL url, String contentType, Map params) throws HttpException { - return callApi(url, "POST", contentType, params); - } - - - /** - * Makes a synchronous PUT request with {@link Http#urlEncodedContentType} contentType - * @param url URL to put to - * @param params Map, a generic Map containing data to put - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_PUT(URL url, Map params) throws HttpException { - return callApi(url, "PUT", HttpService.urlEncodedContentType, params); - } - - - /** - * Makes a synchronous PUT request with specific contentType - * @param url URL to put to - * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. - * @param params Map, a generic Map containing data to put - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_PUT(URL url, String contentType, Map params) throws HttpException { - return callApi(url, "PUT", contentType, params); - } - - - /** - * Makes a synchronous DELETE request - * @param url URL to delete to - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_DELETE(URL url) throws HttpException { - return callApi(url, "DELETE", HttpService.urlEncodedContentType, null); - } - - - /** - * Makes a synchronous DELETE request with parameters and {@link Http#urlEncodedContentType} contentType - * @param url URL to delete to - * @param params Map, a generic Map containing data to put - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_DELETE(URL url, Map params) throws HttpException { - return callApi(url, "DELETE", HttpService.urlEncodedContentType, params); - } - - - /** - * Makes a synchronous DELETE request with parameters and specific contentType - * @param url URL to delete to - * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. - * @param params Map, a generic Map containing data to put - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - public HttpServiceResponse api_DELETE(URL url, String contentType, Map params) throws HttpException { - return callApi(url, "DELETE", contentType, params); - } - - - /** - * Make a synchronous configurable network request. Uses headers and other config from {@link OkHttpService#config} - * @param url URL to call - * @param method String, can be GET, POST, PUT, DELETE, UPDATE - * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType} - * @param params Map, a generic Map with parameters for POST, PUT or UPDATE. Will be serialized according - * to {@code contentType} - * @return {@link HttpServiceResponse} - * @throws HttpException - */ - private HttpServiceResponse callApi(URL url, String method, String contentType, Map params) throws HttpException { - HttpService.NetResponse cache = config.cacheService.getDBResponse(url.toString(), method); - - if(cache != null) { - return new HttpServiceResponse(Utils.stringToContentRep(cache.getResp()), method, contentType, params, config.auth_token); - } - - //http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0 - System.setProperty("jsse.enableSNIExtension", "false"); - - Request.Builder builder = new Request.Builder() - .header("User-Agent", config.userAgent) - .header("App-Id", config.appId) - .header("App-Key", config.appKey) - .url(url.toString()); - - if(config.auth_token != null) - builder.header("Auth-Token", config.auth_token); - - String body = null; - if(params != null) { - try { - body = Http.getEncoder(contentType).encode(params); - } catch (Http.EncodingException | Http.UnknownContentType e) { - throw new HttpException("Error", e) ; - } - } - - if(Objects.equals(method, "POST") && body != null) { - builder.post(RequestBody.create(MediaType.parse(contentType), body)); - } else if(Objects.equals(method, "PUT") && body != null) { - builder.put(RequestBody.create(MediaType.parse(contentType), body)); - } else if(Objects.equals(method, "DELETE") && body != null) { - builder.delete(RequestBody.create(MediaType.parse(contentType), body)); - } else if(Objects.equals(method, "DELETE")) { - builder.delete(); - } - - Request request = builder.build(); - - Response response; - try { - response = client.newCall(request).execute(); - if (!response.isSuccessful()) - throw new HttpException("Unexpected code " + response, response.message(), response.code()); - - String raw_resp = response.body().string(); - config.cacheService.storeResult(url.toString(), method, raw_resp); - - return new HttpServiceResponse(Utils.stringToContentRep(raw_resp), method, contentType, params, config.auth_token); - } catch (IOException e) { - if(e instanceof HttpException) throw (HttpException)e; - throw new HttpException("Error", e) ; - } - - } -} diff --git a/src/main/bookingbugAPI2/api/API.java b/src/main/bookingbugAPI2/api/API.java new file mode 100644 index 0000000..d0ac51f --- /dev/null +++ b/src/main/bookingbugAPI2/api/API.java @@ -0,0 +1,18 @@ +package bookingbugAPI2.api; + +import bookingbugAPI2.services.ServiceProvider; + +/** + * Created by sebi on 19.05.2016. + */ +public class API extends AbstractAPI { + + + public API(ServiceProvider provider) { + super(provider); + } + + public AdminAPI admin() { + return new AdminAPI(newProvider()); + } +} diff --git a/src/main/bookingbugAPI2/api/AbstractAPI.java b/src/main/bookingbugAPI2/api/AbstractAPI.java new file mode 100644 index 0000000..250f917 --- /dev/null +++ b/src/main/bookingbugAPI2/api/AbstractAPI.java @@ -0,0 +1,210 @@ +package bookingbugAPI2.api; + +import bookingbugAPI2.services.http.AbstractHttpService; +import bookingbugAPI2.services.cache.AbstractCacheService; +import bookingbugAPI2.services.cache.SQLiteCacheService; +import bookingbugAPI2.services.ConfigService; +import bookingbugAPI2.services.logger.AbstractLoggerService; +import bookingbugAPI2.services.logger.JavaLoggerService; +import bookingbugAPI2.services.http.OkHttpService; +import bookingbugAPI2.services.ServiceProvider; + +/** + * Abstract API class + * Contains basic methods and members + */ +public abstract class AbstractAPI implements ServiceProvider { + + final String CACHE_TAG; + ServiceProvider provider; + + public AbstractAPI(ServiceProvider provider){ + this.provider = provider; + this.CACHE_TAG = this.getClass().getName(); + } + + /** + * Calls {@link AbstractAPI#fresh(boolean)} with true + * @return API instance + */ + public T fresh() { + return fresh(true); + } + + /** + * Calls {@link bookingbugAPI2.services.cache.AbstractCacheService#setOneTimeFresh(boolean)} + * Disables and clears the cache just for the next api call if {@code fresh} is true + * @return API instance + */ + public T fresh(boolean fresh) { + provider.cacheService().setOneTimeFresh(fresh); + return (T)this; + } + + /** + * Calls {@link AbstractAPI#freshAndClear(boolean)} with true + * @return API instance + */ + public T freshAndClear() { + return freshAndClear(true); + } + + /** + * Calls {@link bookingbugAPI2.services.cache.AbstractCacheService#setOneTimeFresh(boolean)} + * {@link bookingbugAPI2.services.cache.AbstractCacheService#invalidateResultsByTag(String)} + * Disables the cache just for the next call and clears all cache records with same CACHE_TAG if {@code fresh} is true + * Must be called on terminal api instances (CompanyAPI, etc) + * @return + */ + public T freshAndClear(boolean fresh) { + if(fresh) { + provider.cacheService().invalidateResultsByTag(CACHE_TAG); + provider.cacheService().setOneTimeFresh(true); + } + return (T)this; + } + + /** + * Returns an ApiConfig with the same configuration as the current one, except that the ConfigService is a clone + * @return current configuration with ConfigService clone + */ + public ApiConfig newConfig() { + ApiConfig clone = new ApiConfig(provider); + ConfigService newConfig = new ConfigService(provider.configService()); + return clone.withConfigService(newConfig); + } + + public ServiceProvider newProvider() { + return (ServiceProvider)newConfig(); + } + + public String getAuthToken(){ + return provider.configService().auth_token; + } + + @Override + public AbstractHttpService httpService() { + return provider.httpService(); + } + + @Override + public AbstractLoggerService loggerService() { + return provider.loggerService(); + } + + @Override + public AbstractCacheService cacheService() { + return provider.cacheService(); + } + + @Override + public ConfigService configService() { + return provider.configService(); + } + + /** + * Class which holds an API configuration + * @param Keep fluent interface for subclasses + */ + public static class ApiConfig implements ServiceProvider { + + //Services + public AbstractCacheService cacheService; + public AbstractLoggerService loggerService; + public AbstractHttpService httpService; + public ConfigService configService; + + //TODO: fix references to services (same for all instances) + public ApiConfig(ServiceProvider provider) { + this.cacheService = provider.cacheService(); + this.loggerService = provider.loggerService(); + this.httpService = provider.httpService(); + this.configService = provider.configService(); + } + + public ApiConfig() { + //Load default services + configService = new ConfigService(); + configService.loadConfigFile(null); + + httpService = new OkHttpService(this); + cacheService = new SQLiteCacheService(this); + loggerService = new JavaLoggerService(); + } + + public T withNothing() { + /*cacheService = null; + loggerService = null; + httpService = null;*/ + configService = new ConfigService(); + + return (T) this; + } + + public T withAuthToken(String token) { + this.configService.auth_token = token; + return (T)this; + } + + public T withApp(String appId, String appKey) { + this.configService.appId = appId; + this.configService.appKey = appKey; + return (T)this; + } + + public T withUserAgent(String userAgent) { + this.configService.userAgent = userAgent; + return (T)this; + } + + public T withServerUrl(String serverUrl) { + this.configService.serverUrl = serverUrl; + return (T)this; + } + + public T withConfigString(String configString) { + configService.loadConfigFile(configString); + return (T)this; + } + + public T withCacheService(AbstractCacheService cacheService) { + this.cacheService = cacheService; + return (T)this; + } + + public T withConfigService(ConfigService configService) { + this.configService = configService; + return (T)this; + } + + public T withHttpService(AbstractHttpService httpService) { + this.httpService = httpService; + return (T)this; + } + + public T withLoggerService(AbstractLoggerService loggerService) { + this.loggerService = loggerService; + return (T)this; + } + + @Override + public AbstractHttpService httpService() { + return httpService; + } + + @Override + public AbstractLoggerService loggerService() { + return loggerService; + } + + @Override + public AbstractCacheService cacheService() { + return cacheService; + } + + @Override + public ConfigService configService() { + return configService; + } + } +} diff --git a/src/main/bookingbugAPI2/api/AdminAPI.java b/src/main/bookingbugAPI2/api/AdminAPI.java new file mode 100644 index 0000000..112dc4f --- /dev/null +++ b/src/main/bookingbugAPI2/api/AdminAPI.java @@ -0,0 +1,2033 @@ +package bookingbugAPI2.api; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.*; +import bookingbugAPI2.services.ServiceProvider; +import com.damnhandy.uri.template.UriTemplate; +import helpers2.Http; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import rx.Observable; + +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + + +public class AdminAPI extends AbstractAPI { + + AdminURLS urls; + + public AdminAPI(ServiceProvider provider) { + super(provider); + urls = new AdminURLS(provider); + } + + + /** + * Accessor to create an instance of {@link LoginAPI} with current configuration + * + * @return LoginAPI instance + */ + public LoginAPI login() { + return new LoginAPI(provider); + } + + public class LoginAPI extends AbstractAPI { + + public LoginAPI(ServiceProvider provider) { + super(provider); + } + + /** + * Authenticate with email and password + * + * @param email the user email + * @param password the user password + * @return Login instance + * @throws IOException + */ + public Login auth(String email, String password) throws IOException { + URL url = new URL(urls.login().auth().expand()); + Map params = new HashMap<>(); + params.put("email", email); + params.put("password", password); + HttpServiceResponse resp; + try { + resp = httpService().api_POST(url, params); + } catch (HttpException e) { + if (e.getStatusCode() == 400) { + resp = new HttpServiceResponse(Utils.stringToContentRep(e.getRawResponse()), url.toString(), "POST", Http.urlEncodedContentType, params, provider.configService().auth_token); + } else throw e; + } + + return new Login(resp); + } + + public Observable authObs(final String email, final String password) { + return Observable.fromCallable(() -> auth(email, password)); + } + + /** + * Authenticate the company administrator with provided credentials + * + * @param administrator The administrator to login with + * @param email the administrator email + * @param password the administrator password + * @return Login instance + * @throws IOException + */ + public Login authWithCompanyAdministrator(Administrator administrator, String email, String password) throws IOException { + URL url = new URL(administrator.getLoginLink()); + Map params = new HashMap<>(); + params.put("email", email); + params.put("password", password); + return new Login(httpService().api_POST(url, params)); + } + + public Observable authWithCompanyAdministratorObs(final Administrator administrator, final String email, final String password) { + return Observable.fromCallable(() -> authWithCompanyAdministrator(administrator, email, password)); + } + } + + + /** + * Accessor to create an instance of {@link BookingAPI} with current configuration + * + * @return BookingAPI instance + */ + public BookingAPI booking() { + return new BookingAPI(newProvider()); + } + + public class BookingAPI extends AbstractAPI { + + public BookingAPI(ServiceProvider provider) { + super(provider); + } + + /** + * Get a list of admin bookings for a company + * + * @param company The owning company for booking + * @param bLParams The parameters for this call + * @return Collection of bookings + * @throws IOException + */ + public BBCollection bookingList(Company company, BookingParams.List bLParams) throws IOException { + URL url = new URL(Utils.inflateLink(company.getBookingsLink(), bLParams.getParams())); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), getAuthToken(), "bookings", Booking.class); + } + + public Observable> bookingListObs(final Company company, final BookingParams.List bLParams) { + return Observable.fromCallable(() -> bookingList(company, bLParams)); + } + + /** + * Get all details about a specific booking + * + * @param company the company owning the booking + * @param bookingId the id of booking to read + * @return Booking + * @throws IOException + */ + public Booking bookingRead(Company company, String bookingId) throws IOException { + URL url = new URL(AdminURLS.Bookings.bookingRead() + .set("companyId", company.id) + .set("bookingId", bookingId) + .expand()); + return new Booking(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable bookingReadObs(final Company company, final String bookingId) { + return Observable.fromCallable(() -> bookingRead(company, bookingId)); + } + + /** + * Get the edit schema for booking + * + * @param booking + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditBookingSchema(Booking booking) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(booking.getEditLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditBookingSchemaObs(final Booking booking) { + return Observable.fromCallable(() -> getEditBookingSchema(booking)); + } + + /** + * Create a booking for a company with provided parameters + * + * @param company The company for booking + * @param bCParams The parameters to create the booking with + * @return Booking + * @throws IOException + */ + public Booking bookingCreate(Company company, BookingParams.Create bCParams) throws IOException { + String urlStr = AdminURLS.Bookings.bookingCreate().set("companyId", company.id).expand(); + URL url = new URL(urlStr); + + return new Booking(httpService().api_POST(url, bCParams.getParams())); + } + + public Observable bookingCreateObs(final Company company, final BookingParams.Create bCParams) { + return Observable.fromCallable(() -> bookingCreate(company, bCParams)); + } + + /** + * Update a booking + * + * @param booking the booking to update + * @param buParams Contains parameters for booking update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Booking + * @throws IOException + */ + public Booking bookingUpdate(Booking booking, BookingParams.Update buParams) throws IOException { + URL url = new URL(booking.getSelf()); + return new Booking(httpService().api_PUT(url, buParams.getParams(), CACHE_TAG), configService().auth_token); + } + + public Observable bookingUpdateObs(final Booking booking, final BookingParams.Update buParams) { + return Observable.fromCallable(() -> bookingUpdate(booking, buParams)); + } + + /** + * Cancel a booking + * + * @param booking the booking to cancel + * @param params parameters for this call + * @return Booking instance + * @throws IOException + */ + public Booking cancelBooking(Booking booking, BookingParams.Cancel params) throws IOException { + URL url = new URL(booking.getSelf()); + return new Booking(httpService().api_DELETE(url, Http.jsonContentType, params.getParams(), CACHE_TAG)); + } + + public Observable cancelBookingObs(final Booking booking, final BookingParams.Cancel params) { + return Observable.fromCallable(() -> cancelBooking(booking, params)); + } + } + + + /** + * Accessor to create an instance of {@link CompanyAPI} with current configuration + * + * @return CompanyAPI instance + */ + public CompanyAPI company() { + return new CompanyAPI(newProvider()); + } + + public class CompanyAPI extends AbstractAPI { + + + public CompanyAPI(ServiceProvider provider) { + super(provider); + } + + /** + * Load All of the Links and Properties of a Company + * + * @param companyId the id of company + * @return Company + * @throws IOException + */ + public Company companyRead(String companyId) throws IOException { + URL url = new URL(AdminURLS.Company.companyRead(configService().serverUrl).set("companyId", companyId).expand()); + return new Company(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable companyReadObs(final String companyId) { + return Observable.fromCallable(() -> companyRead(companyId)); + } + + /** + * Get the company for specified administrator + * + * @param administrator the administrator for the company + * @return Company + * @throws IOException + */ + public Company getCompanyForAdministrator(Administrator administrator) throws IOException { + URL url = new URL(administrator.getCompanyLink()); + return new Company(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getCompanyForAdministratorObs(final Administrator administrator) { + return Observable.fromCallable(() -> getCompanyForAdministrator(administrator)); + } + + /** + * Return the settings for provided company + * + * @param company the company to retrieve settings for + * @return CompanySettings instance + * @throws IOException + */ + public CompanySettings getSettingsForCompany(Company company) throws IOException { + if (company.getResource("settings") != null) + return new CompanySettings(new HttpServiceResponse(company.getResource("settings"))); + URL url = new URL(company.getSettingsLink()); + return new CompanySettings(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getSettingsForCompanyObs(final Company company) { + return Observable.fromCallable(() -> getSettingsForCompany(company)); + } + + /** + * Get all the events for a company with provided params. Returns as paginated list + * + * @param company The company owning the events + * @param params The params to filter the events + * @return Collection of Event + * @throws IOException + */ + public BBCollection getEventsForCompany(Company company, CompanyParams.EventList params) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getEventsLink()).set(params.getParams()).expand()); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "events", Event.class); + } + + public Observable> getEventsForCompanyObs(final Company company, final CompanyParams.EventList params) { + return Observable.fromCallable(() -> getEventsForCompany(company, params)); + } + } + + + /** + * Accessor to create an instance of {@link ServiceAPI} with current configuration + * + * @return ServiceAPI instance + */ + public ServiceAPI service() { + return new ServiceAPI(newProvider()); + } + + public class ServiceAPI extends AbstractAPI { + + + public ServiceAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * List of Services for a company. Results are returned as a paginated list + * + * @param company The owning company for services + * @param slParams Parameters for this call + * @return Collection of Service + * @throws IOException + */ + public BBCollection serviceList(Company company, ServiceListParams slParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getServicesLink(), slParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "services", Service.class); + } + + public Observable> serviceListObs(final Company company, final ServiceListParams slParams) { + return Observable.fromCallable(() -> serviceList(company, slParams)); + } + + /** + * Load a Specific Service Details + * + * @param company The owning company for service + * @param serviceId the id of service to load + * @return Service + * @throws IOException + */ + public Service serviceRead(Company company, String serviceId) throws IOException { + URL url = new URL(AdminURLS.Service.serviceRead() + .set("companyId", company.id) + .set("serviceId", serviceId) + .expand()); + return new Service(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable serviceReadObs(final Company company, final String serviceId) { + return Observable.fromCallable(() -> serviceRead(company, serviceId)); + } + + /** + * Get schema for creating a new service + * + * @param company The owning company + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewServiceSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getNewServiceLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewServiceSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewServiceSchema(company)); + } + + /** + * Create a service + * + * @param company the company to own the service + * @param sCParams Contains parameters for service creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Service + * @throws IOException + */ + public Service serviceCreate(Company company, ServiceParams.ServiceCreateParams sCParams) throws IOException { + URL url = new URL(company.getServicesLink()); + return new Service(httpService().api_POST(url, sCParams.getParams(), CACHE_TAG)); + } + + public Observable serviceCreateObs(final Company company, final ServiceParams.ServiceCreateParams sCParams) { + return Observable.fromCallable(() -> serviceCreate(company, sCParams)); + } + + /** + * Update a service + * + * @param service the service to update + * @param sUParams Contains parameters for service update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Service + * @throws IOException + */ + public Service serviceUpdate(Service service, ServiceParams.ServiceUpdateParams sUParams) throws IOException { + URL url = new URL(service.getEditLink()); + return new Service(httpService().api_POST(url, sUParams.getParams(), CACHE_TAG)); + } + + public Observable serviceUpdateObs(final Service service, final ServiceParams.ServiceUpdateParams sUParams) { + return Observable.fromCallable(() -> serviceUpdate(service, sUParams)); + } + + /** + * Get a schema for creating a new booking with provided service + * + * @param service The service + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewBookingSchema(Service service) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(service.getNewBookingLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewBookingSchemaObs(final Service service) { + return Observable.fromCallable(() -> getNewBookingSchema(service)); + } + + /** + * Get a schema for editing a service + * + * @param service The service to be edited + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditServiceSchema(Service service) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(service.getEditLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditServiceSchemaObs(final Service service) { + return Observable.fromCallable(() -> getEditServiceSchema(service)); + } + } + + + /** + * Accessor to create an instance of {@link ServiceAPI} with current configuration + * + * @return ServiceAPI instance + */ + public ClientAPI client() { + return new ClientAPI(newProvider()); + } + + public class ClientAPI extends AbstractAPI { + + + public ClientAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * List of Clients for a company. Results are returned as a paginated list + * + * @param company The owning company for clients + * @param clParams Parameters for this call + * @return Collection of Client + * @throws IOException + */ + public BBCollection clientList(Company company, ClientListParams clParams) throws IOException { + URL url = new URL(Utils.inflateLink(company.getClientLink(), clParams.getParams())); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "clients", Client.class); + } + + public Observable> clientListObs(final Company company, final ClientListParams clParams) { + return Observable.fromCallable(() -> clientList(company, clParams)); + } + + /** + * Load a specific client details + * + * @param company The owning company for client + * @param clientId The client's id + * @return Client + * @throws IOException + */ + public Client clientRead(Company company, String clientId) throws IOException { + URL url = new URL(urls.client().clientRead() + .set("companyId", company.id) + .set("clientId", clientId) + .expand()); + return new Client(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable clientReadObs(final Company company, final String clientId) { + return Observable.fromCallable(() -> clientRead(company, clientId)); + } + + /** + * Load a specific client details + * + * @param company The owning company for client + * @param email The client's email + * @return Client + * @throws IOException + */ + public Client clientReadByEmail(Company company, String email) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getClientByEmailLink()).set("email", email).expand()); + return new Client(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable clientReadByEmailObs(final Company company, final String email) { + return Observable.fromCallable(() -> clientReadByEmail(company, email)); + } + + /** + * Get the schema for editing a client + * + * @param client The client to edit + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditClientSchema(Client client) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(client.getEditLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditClientSchemaObs(final Client client) { + return Observable.fromCallable(() -> getEditClientSchema(client)); + } + + /** + * Enable/Disable specific client + * + * @param company The company for the client + * @param ctParams parameters for this call + * @return Client TODO: check return type after 401 is solved + * @throws IOException + */ + public Client clientEnableDisable(Company company, ClientToggleParams ctParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getClientLink()).expand()); + return new Client(httpService().api_PUT(url, Http.urlEncodedContentType, ctParams.getParams(), CACHE_TAG)); + } + + public Observable clientEnableDisableObs(final Company company, final ClientToggleParams ctParams) { + return Observable.fromCallable(() -> clientEnableDisable(company, ctParams)); + } + + /** + * Update a client + * + * @param client the client to update + * @param cuParams Contains parameters for client update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Client + * @throws IOException + */ + public Client clientUpdate(Client client, ClientParams.Update cuParams) throws IOException { + URL url = new URL(client.getSelf()); + return new Client(httpService().api_PUT(url, cuParams.getParams(), CACHE_TAG)); + } + + public Observable clientUpdateObs(final Client client, final ClientParams.Update cuParams) { + return Observable.fromCallable(() -> clientUpdate(client, cuParams)); + } + + /** + * Create a client + * + * @param company the company for client + * @param clParams Contains parameters for client creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Client + * @throws IOException + */ + public Client clientCreate(Company company, ClientParams.Create clParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getClientLink()).expand()); + return new Client(httpService().api_POST(url, clParams.getParams(), CACHE_TAG)); + } + + public Observable clientCreateObs(final Company company, final ClientParams.Create clParams) { + return Observable.fromCallable(() -> clientCreate(company, clParams)); + } + + } + + + /** + * Accessor to create an instance of {@link ResourceAPI} with current configuration + * + * @return ResourceAPI instance + */ + public ResourceAPI resource() { + return new ResourceAPI(newProvider()); + } + + public class ResourceAPI extends AbstractAPI { + + public ResourceAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Load specific resource details + * + * @param company + * @param resourceId + * @return Resource + * @throws IOException + */ + public Resource resourceRead(Company company, String resourceId) throws IOException { + URL url = new URL(AdminURLS.Resource.resourceRead() + .set("companyId", company.id) + .set("resourceId", resourceId) + .expand()); + return new Resource(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable resourceReadObs(final Company company, final String resourceId) { + return Observable.fromCallable(() -> resourceRead(company, resourceId)); + } + + /** + * List of Resources for a company. Results are returned as a paginated list + * + * @param company The owning company for services + * @param rlParams Parameters for this call + * @return Collection of Resource + * @throws IOException + */ + public BBCollection resourceList(Company company, Params rlParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getResourcesLink(), rlParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "resources", Resource.class); + } + + public Observable> resourceListObs(final Company company, final Params rlParams) { + return Observable.fromCallable(() -> resourceList(company, rlParams)); + } + + /** + * Create a new resource + * + * @param company the company for resource + * @param rcParams Contains parameters for resource creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Resource + * @throws IOException + */ + public Resource resourceCreate(Company company, ResourceParams.Create rcParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getResourcesLink()).expand()); + return new Resource(httpService().api_POST(url, rcParams.getParams(), CACHE_TAG)); + } + + public Observable resourceCreateObs(final Company company, final ResourceParams.Create rcParams) { + return Observable.fromCallable(() -> resourceCreate(company, rcParams)); + } + + /** + * Update a resource + * + * @param resource the resource to update + * @param ruParams Contains parameters for resource update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Resource + * @throws IOException + */ + public Resource resourceUpdate(Resource resource, ResourceParams.Update ruParams) throws IOException { + URL url = new URL(resource.getSelf()); + return new Resource(httpService().api_PUT(url, ruParams.getParams(), CACHE_TAG)); + } + + public Observable resourceUpdateObs(final Resource resource, final ResourceParams.Update ruParams) { + return Observable.fromCallable(() -> resourceUpdate(resource, ruParams)); + } + + /** + * Get the schema for creating a new resource + * + * @param company The company to own the resource + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewResourceSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getNewResourceLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewResourceSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewResourceSchema(company)); + } + + /** + * Get the schema for editing a resource + * + * @param resource The resource to edit + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditResourceSchema(Resource resource) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(resource.getEditLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditResourceSchemaObs(final Resource resource) { + return Observable.fromCallable(() -> getEditResourceSchema(resource)); + } + + //TODO: Add block and schedule calls + } + + + /** + * Accessor to create an instance of {@link EventChainAPI} with current configuration + * + * @return EventChainAPI instance + */ + public EventChainAPI eventChain() { + return new EventChainAPI(newProvider()); + } + + public class EventChainAPI extends AbstractAPI { + public EventChainAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Load specific event chain details + * + * @param company + * @param eventChainId + * @return EventChain + * @throws IOException + */ + public EventChain eventChainRead(Company company, String eventChainId) throws IOException { + URL url = new URL(AdminURLS.EventChain.eventChainRead() + .set("companyId", company.id) + .set("eventChainId", eventChainId) + .expand()); + return new EventChain(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable eventChainReadObs(final Company company, final String eventChainId) { + return Observable.fromCallable(() -> eventChainRead(company, eventChainId)); + } + + /** + * Load specific event chain details by reference + * + * @param company + * @param refId the reference to the event chain to read + * @return EventChain + * @throws IOException + */ + public EventChain eventChainReadByRefId(Company company, String refId) throws IOException { + URL url = new URL(AdminURLS.EventChain.eventChainReadUsingRefId() + .set("companyId", company.id) + .set("refId", refId) + .expand()); + return new EventChain(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable eventChainReadByRefIdObs(final Company company, final String refId) { + return Observable.fromCallable(() -> eventChainReadByRefId(company, refId)); + } + + /** + * List of event chains for a company. Results are returned as a paginated list + * + * @param company The owning company for services + * @param rlParams Parameters for this call + * @return Collection of EventChain + * @throws IOException + */ + public BBCollection eventChainList(Company company, Params rlParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getEventChainsLink(), rlParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "event_chains", EventChain.class); + } + + public Observable> eventChainListObs(final Company company, final Params rlParams) { + return Observable.fromCallable(() -> eventChainList(company, rlParams)); + } + + /** + * Create a new event chain + * + * @param company the company for event chain + * @param eccParams Contains parameters for event chain creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return EventChain + * @throws IOException + */ + public EventChain eventChainCreate(Company company, EventChainParams.Create eccParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getEventChainsLink()).expand()); + return new EventChain(httpService().api_POST(url, eccParams.getParams(), CACHE_TAG)); + } + + public Observable eventChainCreateObs(final Company company, final EventChainParams.Create rcParams) { + return Observable.fromCallable(() -> eventChainCreate(company, rcParams)); + } + + /** + * Update an event chain + * + * @param eventChain the event chain to update + * @param ecuParams Contains parameters for event chain update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return EventChain + * @throws IOException + */ + + public EventChain eventChainUpdate(EventChain eventChain, EventChainParams.Update ecuParams) throws IOException { + URL url = new URL(eventChain.getSelf()); + return new EventChain(httpService().api_PUT(url, ecuParams.getParams(), CACHE_TAG)); + } + + public Observable eventChainUpdateObs(final EventChain eventChain, final EventChainParams.Update ruParams) { + return Observable.fromCallable(() -> eventChainUpdate(eventChain, ruParams)); + } + + + /** + * Get a schema for editing a eventChain + * + * @param company + * @param eventChainId the event chain to edit + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditEventChainSchema(Company company, String eventChainId) throws IOException { + URL url = new URL(AdminURLS.EventChain.eventChainEdit() + .set("companyId", company.id) + .set("eventChainId", eventChainId) + .expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditEventChainSchemaObs(final Company company, final String eventChainId) { + return Observable.fromCallable(() -> getEditEventChainSchema(company, eventChainId)); + } + + /** + * Get the schema for creating a new event chain + * + * @param company The company to own the event chain + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewEventChainSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getEventChainsLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewEventChainSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewEventChainSchema(company)); + } + + /** + * Get the events for an eventChain + * + * @param eventChain The eventChain for events + * @param params Pagination params + * @return Collection of Event + * @throws IOException + */ + public BBCollection getEventsForEventChain(EventChain eventChain, Params params) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(eventChain.getEventsLink(), params); + URL url = new URL(template.expand()); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "events", Event.class); + } + + public Observable> getEventsForEventChainObs(final EventChain eventChain, final Params params) { + return Observable.fromCallable(() -> getEventsForEventChain(eventChain, params)); + } + } + + + /** + * Accessor to create an instance of {@link EventGroupAPI} with current configuration + * + * @return EventGroupAPI instance + */ + public EventGroupAPI eventGroup() { + return new EventGroupAPI(newProvider()); + } + + public class EventGroupAPI extends AbstractAPI { + public EventGroupAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Load specific event group details + * + * @param company + * @param eventGroupId + * @return EventGroup + * @throws IOException + */ + public EventGroup eventGroupRead(Company company, String eventGroupId) throws IOException { + URL url = new URL(AdminURLS.EventGroup.eventGroupRead() + .set("companyId", company.id) + .set("eventGroupId", eventGroupId) + .expand()); + return new EventGroup(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable eventGroupReadObs(final Company company, final String eventGroupId) { + return Observable.fromCallable(() -> eventGroupRead(company, eventGroupId)); + } + + /** + * List of event groups for a company. Results are returned as a paginated list + * + * @param company The owning company for services + * @param rlParams Parameters for this call + * @return Collection of EventGroup + * @throws IOException + */ + public BBCollection eventGroupList(Company company, Params rlParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getEventGroupsLink(), rlParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "eventGroups", EventGroup.class); + } + + public Observable> eventGroupListObs(final Company company, final Params rlParams) { + return Observable.fromCallable(() -> eventGroupList(company, rlParams)); + } + + /** + * Get a schema for editing a eventGroup + * + * @param company + * @param eventGroupId the event group to edit + * @return + * @throws IOException + */ + public SchemaForm getEditEventGroupSchema(Company company, String eventGroupId) throws IOException { + URL url = new URL(AdminURLS.EventGroup.eventGroupEdit() + .set("companyId", company.id) + .set("eventGroupId", eventGroupId) + .expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditEventGroupSchemaObs(final Company company, final String eventGroupId) { + return Observable.fromCallable(() -> getEditEventGroupSchema(company, eventGroupId)); + } + + /** + * Get the schema for creating a new event group + * + * @param company The company to own the event group + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewEventGroupSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getEventGroupsLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewEventGroupSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewEventGroupSchema(company)); + } + } + + + /** + * Accessor to create an instance of {@link EventAPI} with current configuration + * + * @return EventAPI instance + */ + public EventAPI event() { + return new EventAPI(newProvider()); + } + + public class EventAPI extends AbstractAPI { + + public EventAPI(ServiceProvider provider) { + super(provider); + } + + /** + * Get a schema for creating a new booking with provided event + * + * @param event The event + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewBookingSchema(Event event) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(event.getNewBookingLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewBookingSchemaObs(final Event event) { + return Observable.fromCallable(() -> getNewBookingSchema(event)); + } + } + + /** + * Accessor to create an instance of {@link ScheduleAPI} with current configuration + * + * @return ScheduleAPI instance + */ + public ScheduleAPI schedule() { + return new ScheduleAPI(newProvider()); + } + + public class ScheduleAPI extends AbstractAPI { + + public ScheduleAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Get a list of admin schedules for a company + * + * @param company The owning company for schedule + * @param sLParams The parameters for this call + * @return Collection of Schedule + * @throws IOException + */ + public BBCollection scheduleList(Company company, Params sLParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getSchedulesLink(), sLParams); + URL url = new URL(template.expand()); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), getAuthToken(), "schedules", Schedule.class); + } + + public Observable> scheduleListObs(final Company company, final Params sLParams) { + return Observable.fromCallable(() -> scheduleList(company, sLParams)); + } + + /** + * Create a schedule + * + * @param company the company to own the schedule + * @param sCParams Contains parameters for schedule creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Service + * @throws IOException + */ + public Schedule scheduleCreate(Company company, ScheduleParams.Create sCParams) throws IOException { + URL url = new URL(company.getSchedulesLink()); + return new Schedule(httpService().api_POST(url, sCParams.getParams(), CACHE_TAG)); + } + + public Observable scheduleCreateObs(final Company company, final ScheduleParams.Create sCParams) { + return Observable.fromCallable(() -> scheduleCreate(company, sCParams)); + } + + /** + * Get schema for creating a new schedule + * + * @param company The owning company + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewScheduleSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getNewScheduleLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewScheduleSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewScheduleSchema(company)); + } + + /** + * Delete a schedule + * + * @param company The owning company + * @param scheduleId The id of schedule + * @return Schedule + * @throws IOException + */ + public Schedule deleteSchedule(Company company, String scheduleId) throws IOException { + URL url = new URL(AdminURLS.Schedule.scheduleDelete() + .set("companyId", company.id) + .set("scheduleId", scheduleId) + .expand()); + return new Schedule(httpService().api_DELETE(url, CACHE_TAG)); + } + + public Observable deleteScheduleObs(final Company company, final String scheduleID) { + return Observable.fromCallable(() -> deleteSchedule(company, scheduleID)); + } + + /** + * Get all details about a specific schedule + * + * @param company the company owning the schedule + * @param scheduleId the id of schedule to read + * @return Schedule + * @throws IOException + */ + public Schedule scheduleRead(Company company, String scheduleId) throws IOException { + URL url = new URL(AdminURLS.Schedule.scheduleRead() + .set("companyId", company.id) + .set("scheduleId", scheduleId) + .expand()); + return new Schedule(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable scheduleReadObs(final Company company, final String scheduleId) { + return Observable.fromCallable(() -> scheduleRead(company, scheduleId)); + } + + /** + * Update a schedule + * + * @param company the company owning the schedule + * @param scheduleId the schedule to update + * @param sUParams Contains parameters for schedule update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Schedule + * @throws IOException + */ + public Schedule scheduleUpdate(Company company, String scheduleId, ScheduleParams.Update sUParams) throws IOException { + URL url = new URL(AdminURLS.Schedule.scheduleUpdate() + .set("companyId", company.id) + .set("scheduleId", scheduleId) + .expand()); + + return new Schedule(httpService().api_PUT(url, sUParams.getParams(), CACHE_TAG)); + } + + public Observable scheduleUpdateObs(final Company company, final String scheduleId, final ScheduleParams.Update sUParams) { + return Observable.fromCallable(() -> scheduleUpdate(company, scheduleId, sUParams)); + } + + /** + * Get the edit schema for schedule + * + * @param company the company owning the schedule + * @param scheduleId the id of schedule to edit + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditScheduleSchema(Company company, String scheduleId) throws IOException { + URL url = new URL(AdminURLS.Schedule.scheduleEdit() + .set("companyId", company.id) + .set("scheduleId", scheduleId) + .expand()); + + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditScheduleSchemaObs(Company company, String scheduleId) { + return Observable.fromCallable(() -> getEditScheduleSchema(company, scheduleId)); + } + } + + + /** + * Accessor to create an instance of {@link AddressAPI} with current configuration + * + * @return AddressAPI instance + */ + public AddressAPI address() { + return new AddressAPI(newProvider()); + } + + public class AddressAPI extends AbstractAPI { + + public AddressAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Get a list of addresses for a company + * + * @param company The owning company for address + * @param aLParams The parameters for this call + * @return Collection of Address + * @throws IOException + */ + public BBCollection
addressList(Company company, Params aLParams) throws IOException { + URL url = new URL(Utils.inflateLink(company.getAddressesLink(), aLParams.getParams())); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), getAuthToken(), "addresses", Address.class); + } + + public Observable> addressListObs(final Company company, final Params aLParams) { + return Observable.fromCallable(() -> addressList(company, aLParams)); + } + + /** + * Create an address + * + * @param company the company to own the address + * @param aCParams Contains parameters for address creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Address + * @throws IOException + */ + public Address addressCreate(Company company, AddressParams.Create aCParams) throws IOException { + URL url = new URL(company.getAddressLink()); + return new Address(httpService().api_POST(url, aCParams.getParams(), CACHE_TAG)); + } + + public Observable
addressCreateObs(final Company company, final AddressParams.Create sCParams) { + return Observable.fromCallable(() -> addressCreate(company, sCParams)); + } + + /** + * Delete an address + * + * @param company the company to own the address + * @param addressId the address id + * @return SchemaForm + * @throws IOException + */ + public Address deleteAddress(Company company, String addressId) throws IOException { + URL url = new URL(AdminURLS.Address.addressDelete() + .set("companyId", company.id) + .set("addressId", addressId) + .expand()); + return new Address(httpService().api_DELETE(url, CACHE_TAG)); + } + + public Observable
deleteAddressObs(final Company company, final String addressID) { + return Observable.fromCallable(() -> deleteAddress(company, addressID)); + } + + /** + * Get all details about a specific address + * + * @param company the company owning the address + * @param addressId the id of address to read + * @return Address + * @throws IOException + */ + public Address addressRead(Company company, String addressId) throws IOException { + URL url = new URL(AdminURLS.Address.addressRead() + .set("companyId", company.id) + .set("addressId", addressId) + .expand()); + return new Address(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable
addressReadObs(final Company company, final String addressId) { + return Observable.fromCallable(() -> addressRead(company, addressId)); + } + + /** + * Update an address + * + * @param company the company owning the address + * @param sUParams Contains parameters for address update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Address + * @throws IOException + */ + public Address addressUpdate(Company company, AddressParams.Update sUParams) throws IOException { + URL url = new URL(company.getAddressLink()); + + return new Address(httpService().api_PUT(url, sUParams.getParams(), CACHE_TAG)); + } + + public Observable
addressUpdateObs(final Company company, final AddressParams.Update sUParams) { + return Observable.fromCallable(() -> addressUpdate(company, sUParams)); + } + } + + + /** + * Accessor to create an instance of {@link AdministratorAPI} with current configuration + * + * @return AdministratorAPI instance + */ + public AdministratorAPI administrator() { + return new AdministratorAPI(newProvider()); + } + + public class AdministratorAPI extends AbstractAPI { + + public AdministratorAPI(ServiceProvider provider) { + super(provider); + } + + /** + * Get the administrator for a specific login. It searches in embedded objects and if not found calls + * the administrator link + * + * @param login The login + * @return Administrator instance + * @throws IOException + */ + public Administrator getAdministratorForLogin(Login login) throws IOException { + String adminLink = login.getAdministratorLink(); + BBCollection admins = login.getAdministrators(); + //search embedded object + for (Administrator admin : admins) { + if (admin.getSelf().equals(adminLink)) + return admin; + } + URL url = new URL(adminLink); + return new Administrator(httpService().api_GET(url, CACHE_TAG), getAuthToken()); + } + + public Observable getAdministratorForLoginObs(Login login) { + return Observable.fromCallable(() -> getAdministratorForLogin(login)); + } + + /** + * Get a list of administrators for a company + * + * @param company The owning company for administrator + * @param aLParams The parameters for this call + * @return Collection of Administrator + * @throws IOException + */ + public BBCollection administratorList(Company company, Params aLParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getAdministratorsLink(), aLParams); + URL url = new URL(template.expand()); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), getAuthToken(), "administrators", Administrator.class); + } + + public Observable> administratorListObs(final Company company, final Params aLParams) { + return Observable.fromCallable(() -> administratorList(company, aLParams)); + } + + /** + * Create an administrator + * + * @param company the company to own the administrator + * @param aCParams Contains parameters for administrator creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Administrator + * @throws IOException + */ + public Administrator administratorCreate(Company company, AdministratorParams.Create aCParams) throws IOException { + URL url = new URL(AdminURLS.Administrator.administratorCreate() + .set("companyId", company.id) + .expand()); + + return new Administrator(httpService().api_POST(url, aCParams.getParams(), CACHE_TAG)); + } + + public Observable administratorCreateObs(final Company company, final AdministratorParams.Create aCParams) { + return Observable.fromCallable(() -> administratorCreate(company, aCParams)); + } + + /** + * Delete an administrator + * + * @param company The owning company + * @param administratorId the id of administrator to be deleted + * @return SchemaForm + * @throws IOException + */ + public Administrator deleteAdministrator(Company company, String administratorId) throws IOException { + URL url = new URL(AdminURLS.Administrator.administratorDelete() + .set("companyId", company.id) + .set("administratorId", administratorId) + .expand()); + return new Administrator(httpService().api_DELETE(url, CACHE_TAG)); + } + + public Observable deleteAdministratorObs(final Company company, final String administratorID) { + return Observable.fromCallable(() -> deleteAdministrator(company, administratorID)); + } + + /** + * Get all details about a specific administrator + * + * @param company the company owning the administrator + * @param administratorId the id of administrator to read + * @return Administrator + * @throws IOException + */ + public Administrator administratorRead(Company company, String administratorId) throws IOException { + URL url = new URL(AdminURLS.Administrator.administratorRead() + .set("companyId", company.id) + .set("administratorId", administratorId) + .expand()); + return new Administrator(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable administratorReadObs(final Company company, final String administratorId) { + return Observable.fromCallable(() -> administratorRead(company, administratorId)); + } + + /** + * Update an administrator + * + * @param company the company owning the administrator + * @param aUParams Contains parameters for administrator update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Administrator + * @throws IOException + */ + public Administrator administratorUpdate(Company company, String adminId, AdministratorParams.Update aUParams) throws IOException { + URL url = new URL(AdminURLS.Administrator.administratorUpdate() + .set("companyId", company.id) + .set("adminId", adminId) + .expand()); + return new Administrator(httpService().api_PUT(url, aUParams.getParams(), CACHE_TAG)); + } + + public Observable administratorUpdateObs(final Company company, final String adminId, final AdministratorParams.Update aUParams) { + return Observable.fromCallable(() -> administratorUpdate(company, adminId, aUParams)); + } + + /** + * Get the edit schema for administrator + * + * @param administrator + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditAdministratorSchema(Administrator administrator) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(administrator.getEditLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditAdministratorSchemaObs(final Administrator administrator) { + return Observable.fromCallable(() -> getEditAdministratorSchema(administrator)); + } + + /** + * Get schema for creating a new administrator + * + * @param company The owning company + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewAdministratorSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getNewAdministratorLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewAdministratorSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewAdministratorSchema(company)); + } + } + + + /** + * Accessor to create an instance of {@link PersonAPI} with current configuration + * + * @return PersonAPI instance + */ + public PersonAPI person() { + return new PersonAPI(newProvider()); + } + + public class PersonAPI extends AbstractAPI { + public PersonAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Load a specific person details by reference + * + * @param company + * @param personId + * @return + * @throws IOException + */ + public Person personRead(Company company, String personId) throws IOException { + URL url = new URL(AdminURLS.Person.personRead() + .set("companyId", company.id) + .set("personId", personId) + .expand()); + return new Person(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable personReadObs(final Company company, final String refId) { + return Observable.fromCallable(() -> personRead(company, refId)); + } + + /** + * Load specific person details by reference + * + * @param company + * @param refId the reference to the person to read + * @return People + * @throws IOException + */ + public Person personReadByRefId(Company company, String refId) throws IOException { + URL url = new URL(AdminURLS.Person.personReadUsingRefId() + .set("companyId", company.id) + .set("refId", refId) + .expand()); + return new Person(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable personReadByRefIdObs(final Company company, final String refId) { + return Observable.fromCallable(() -> personReadByRefId(company, refId)); + } + + /** + * List of persons for a company. Results are returned as a paginated list + * + * @param company The owning company for people + * @param plParams Parameters for this call + * @return Collection of People + * @throws IOException + */ + public BBCollection personList(Company company, Params plParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getPeopleLink(), plParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "people", Person.class); + } + + public Observable> personListObs(final Company company, final Params plParams) { + return Observable.fromCallable(() -> personList(company, plParams)); + } + + /** + * Create a new person + * + * @param company the company for person + * @param pcParams Contains parameters for person creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return People + * @throws IOException + */ + public Person personCreate(Company company, PersonParams.Create pcParams) throws IOException { + URL url = new URL(AdminURLS.Person.personCreate() + .set("companyId", company.id) + .expand()); + return new Person(httpService().api_POST(url, pcParams.getParams(), CACHE_TAG)); + } + + public Observable personCreateObs(final Company company, final PersonParams.Create rcParams) { + return Observable.fromCallable(() -> personCreate(company, rcParams)); + } + + /** + * Update a person + * + * @param company the company the person is part of. + * @param personId the person to update + * @param puParams Contains parameters for person update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return People + * @throws IOException + */ + + public Person personUpdate(Company company, String personId, PersonParams.Update puParams) throws IOException { + URL url = new URL(AdminURLS.Person.personUpdate() + .set("companyId", company.id) + .set("personId", personId) + .expand()); + return new Person(httpService().api_PUT(url, puParams.getParams(), CACHE_TAG)); + } + + public Observable personUpdateObs(final Company company, final String personId, final PersonParams.Update puParams) { + return Observable.fromCallable(() -> personUpdate(company, personId, puParams)); + } + + + /** + * Get a schema for editing a person + * + * @param person the person to edit + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getEditPersonSchema(Person person) throws IOException { + URL url = new URL(person.getEditLink()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getEditPersonSchemaObs(final Person person) { + return Observable.fromCallable(() -> getEditPersonSchema(person)); + } + + /** + * Get the schema for creating a new person + * + * @param company The company to own the person + * @return SchemaForm + * @throws IOException + */ + public SchemaForm getNewPersonSchema(Company company) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getNewPersonLink()).expand()); + return new SchemaForm(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable getNewPersonSchemaObs(final Company company) { + return Observable.fromCallable(() -> getNewPersonSchema(company)); + } + + /** + * Set a staff member attendance + * + * @param company the company the person is part of. + * @param personId the person to update + * @return People + * @throws IOException + */ + + public Person setPersonAttendance(Company company, String personId, PersonParams.Update puParams) throws IOException { + URL url = new URL(new Person().getAttendanceLink()); + return new Person(httpService().api_PUT(url, puParams.getParams(), CACHE_TAG)); + } + + public Observable setPersonAttendanceObs(final Company company, final String personId, final PersonParams.Update puParams) { + return Observable.fromCallable(() -> personUpdate(company, personId, puParams)); + } + + // TODO: 15.07.2016 Test setPersonAttendance + + // TODO: 15.07.2016 Implement getQueuersToAMember() + } + + + /** + * Accessor to create an instance of {@link ClinicAPI} with current configuration + * + * @return ClinicAPI instance + */ + public ClinicAPI clinic() { + return new ClinicAPI(newProvider()); + } + + public class ClinicAPI extends AbstractAPI { + + public ClinicAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * Load specific clinic details + * + * @param company + * @param clinicId + * @return Clinic + * @throws IOException + */ + public Clinic clinicRead(Company company, String clinicId) throws IOException { + URL url = new URL(AdminURLS.Clinic.clinicRead() + .set("companyId", company.id) + .set("clinicId", clinicId) + .expand()); + return new Clinic(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable clinicReadObs(final Company company, final String clinicId) { + return Observable.fromCallable(() -> clinicRead(company, clinicId)); + } + + /** + * List of clinics for a company. Results are returned as a paginated list + * + * @param company The owning company for services + * @param clParams Parameters for this call + * @return Collection of Clinic + * @throws IOException + */ + public BBCollection clinicList(Company company, Params clParams) throws IOException { + UriTemplate template = Utils.TemplateWithPagination(company.getClinicsLink(), clParams); + URL url = new URL(template.expand()); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "clinics", Clinic.class); + } + + public Observable> clinicListObs(final Company company, final Params rlParams) { + return Observable.fromCallable(() -> clinicList(company, rlParams)); + } + + /** + * Create a new clinic + * + * @param company the company for clinic + * @param ccParams Contains parameters for clinic creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Clinic + * @throws IOException + */ + public Clinic clinicCreate(Company company, ClinicParams.Create ccParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getClinicsLink()).expand()); + return new Clinic(httpService().api_POST(url, ccParams.getParams(), CACHE_TAG)); + } + + public Observable clinicCreateObs(final Company company, final ClinicParams.Create rcParams) { + return Observable.fromCallable(() -> clinicCreate(company, rcParams)); + } + + /** + * Cancel a clinic + * + * @param company the company for clinic + * @param clinicId the clinic to cancel + * @return Clinic + * @throws IOException + */ + public Clinic clinicCancel(Company company, String clinicId, Params ccparams) throws IOException { + URL url = new URL(AdminURLS.Clinic.clinicCancel() + .set("companyId", company.id) + .set("clinicID", clinicId) + .expand()); + return new Clinic(httpService().api_POST(url, ccparams.getParams(), CACHE_TAG)); + } + + public Observable clinicCancelObs(final Company company, String clinicId, Params ccParams) { + return Observable.fromCallable(() -> clinicCancel(company, clinicId, ccParams)); + } + + /** + * Update a clinic + * + * @param clinic the clinic to update + * @param cuParams Contains parameters for clinic update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Clinic + * @throws IOException + */ + public Clinic clinicUpdate(Clinic clinic, ClinicParams.Update cuParams) throws IOException { + URL url = new URL(clinic.getSelf()); + return new Clinic(httpService().api_PUT(url, cuParams.getParams(), CACHE_TAG)); + } + + public Observable clinicUpdateObs(final Clinic clinic, final ClinicParams.Update cuParams) { + return Observable.fromCallable(() -> clinicUpdate(clinic, cuParams)); + } + } + + + /** + * Accessor to create an instance of {@link PurchaseAPI} with current configuration + * + * @return PurchaseAPI instance + */ + public PurchaseAPI purchase() { + return new PurchaseAPI(newProvider()); + } + + public class PurchaseAPI extends AbstractAPI { + + public PurchaseAPI(ServiceProvider provider) { + super(provider); + } + + /** + * List of purchases for a company + * + * @param company The owning company for services + * @param plParams Parameters for this call + * @return Collection of Purchase + * @throws IOException + */ + public BBCollection purchaseList(Company company, PurchaseListParams plParams) throws IOException { + UriTemplate template = AdminURLS.Purchase.purchaseList() + .set("companyId", company.id) + .set(plParams.getParams()); + URL url = new URL(template.expand()); + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "purchases", Purchase.class); + } + + public Observable> purchaseListObs(final Company company, final PurchaseListParams plParams) { + return Observable.fromCallable(() -> purchaseList(company, plParams)); + } + + /** + * Get all details about a specific purchase + * + * @param company the company that owns the purchase + * @param purchaseId the purchase to read + * @return Purchase + * @throws IOException + */ + public Purchase purchaseRead(Company company, String purchaseId) throws IOException { + URL url = new URL(AdminURLS.Purchase.purchaseRead() + .set("companyId", company.id) + .set("purchaseId", purchaseId) + .expand()); + + return new Purchase(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable purchaseReadObs(final Company company, String purchaseId) { + return Observable.fromCallable(() -> purchaseRead(company, purchaseId)); + } + + /** + * Make a purchase as paid + * + * @param company the company that owns the purchase + * @param purchaseId the purchase to mark as paid + * @param ppParams + * @return Purchase + * @throws IOException + */ + public Purchase purchasePay(Company company, String purchaseId, PurchaseParams ppParams) throws IOException { + URL url = new URL(AdminURLS.Purchase.purchasePay() + .set("companyId", company.id) + .set("purchaseId", purchaseId) + .expand()); + + return new Purchase(httpService().api_PUT(url, ppParams.getParams(), CACHE_TAG)); + } + + public Observable purchasePayObs(final Company company, final String purchaseId, final PurchaseParams ppParams) { + return Observable.fromCallable(() -> purchasePay(company, purchaseId, ppParams)); + } + } + + + /** + * Accessor to create an instance of {@link QuestionAPI} with current configuration + * + * @return QuestionAPI instance + */ + public QuestionAPI question() { + return new QuestionAPI(newProvider()); + } + + public class QuestionAPI extends AbstractAPI { + public QuestionAPI(ServiceProvider provider) { + super(provider); + } + + /** + * List of questions for a company + * + * @param company The owning company for questions + * @param qlParams Parameters for this call + * @return Collection of Question + * @throws IOException + */ + public BBCollection questionList(Company company, QuestionListParams qlParams) throws IOException { + URL url = new URL(Utils.inflateLink(AdminURLS.Question.questionList() + .set("companyId", company.id).expand(), qlParams.getParams())); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "questions", Question.class); + } + + public Observable> questionListObs(final Company company, final QuestionListParams qlParams) { + return Observable.fromCallable(() -> questionList(company, qlParams)); + } + } + + + /** + * Accessor to create an instance of {@link SessionAPI} with current configuration + * + * @return SessionAPI instance + */ + public SessionAPI session() { + return new SessionAPI(newProvider()); + } + + public class SessionAPI extends AbstractAPI { + public SessionAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * List of sessions for a company + * + * @param company The owning company for sessions + * @param slParams Parameters for this call + * @return Collection of Session + * @throws IOException + */ + public BBCollection sessionList(Company company, SessionListParams slParams) throws IOException { + URL url = new URL(Utils.inflateLink(AdminURLS.Session.sessionList() + .set("companyId", company.id) + .expand(), slParams.getParams())); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "sessions", Session.class); + } + + /** + * Get all details about a specific session + * + * @param company the company that owns the session + * @param sessionId the session to read + * @return Session + * @throws IOException + */ + public Session sessionRead(Company company, String sessionId) throws IOException { + URL url = new URL(AdminURLS.Session.sessionRead() + .set("companyId", company.id) + .set("sessionId", sessionId) + .expand()); + + return new Session(httpService().api_GET(url, CACHE_TAG)); + } + } + + + /** + * Accessor to create an instance of {@link SlotAPI} with current configuration + * + * @return SlotAPI instance + */ + public SlotAPI slot() { + return new SlotAPI(newProvider()); + } + + public class SlotAPI extends AbstractAPI { + public SlotAPI(ServiceProvider provider) { + super(provider); + } + + + /** + * List of slots for a company. Results are returned as a paginated list + * + * @param company The owning company for slots + * @param slParams Parameters for this call + * @return Collection of Slot + * @throws IOException + */ + public BBCollection slotList(Company company, SlotListParams slParams) throws IOException { + URL url = new URL(Utils.inflateLink(AdminURLS.Slot.slotList() + .set("companyId", company.id) + .expand(), slParams.getParams())); + + return new BBCollection<>(httpService().api_GET(url, CACHE_TAG), configService().auth_token, "slots", Slot.class); + } + + public Observable> slotListObs(final Company company, final SlotListParams slParams) { + return Observable.fromCallable(() -> slotList(company, slParams)); + } + + /** + * Create a new slot + * + * @param company the company for slot + * @param scParams Contains parameters for slot creation. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Slot + * @throws IOException + */ + public Slot slotCreate(Company company, SlotParams.Create scParams) throws IOException { + URL url = new URL(UriTemplate.fromTemplate(company.getSlotsLink()).expand()); + return new Slot(httpService().api_POST(url, scParams.getParams(), CACHE_TAG)); + } + + public Observable slotCreateObs(final Company company, final SlotParams.Create scParams) { + return Observable.fromCallable(() -> slotCreate(company, scParams)); + } + + /** + * Cancel a slot + * + * @param company the company for slot + * @param slotId the slot to cancel + * @return SchemaForm + * @throws IOException + */ + public Slot deleteSlot(Company company, String slotId) throws IOException { + URL url = new URL(AdminURLS.Slot.slotDelete() + .set("companyId", company.id) + .set("slotID", slotId) + .expand()); + return new Slot(httpService().api_DELETE(url, CACHE_TAG)); + } + + public Observable deleteSlotObs(final Company company, String slotId) { + return Observable.fromCallable(() -> deleteSlot(company, slotId)); + } + + /** + * Get all the details about a specific slot + * + * @param company the company that owns the slot + * @param slotId the slot to read + * @return Slot + * @throws IOException + */ + public Slot slotRead(Company company, String slotId) throws IOException { + URL url = new URL(AdminURLS.Slot.slotRead() + .set("companyId", company.id) + .set("slotId", slotId) + .expand()); + + return new Slot(httpService().api_GET(url, CACHE_TAG)); + } + + public Observable slotReadObs(final Company company, final String slotId) { + return Observable.fromCallable(() -> slotRead(company, slotId)); + } + + /** + * Update a slot + * + * @param slot the slot to update + * @param suParams Contains parameters for slot update. If the schema is used, then set the json form output + * to this through {@link bookingbugAPI2.models.params.Params#setJson(String)} + * in order to ignore declared fields + * @return Slot + * @throws IOException + */ + public Slot slotUpdate(Slot slot, SlotParams.Update suParams) throws IOException { + URL url = new URL(slot.getSelf()); + return new Slot(httpService().api_PUT(url, suParams.getParams(), CACHE_TAG)); + } + + public Observable slotUpdateObs(final Slot slot, final SlotParams.Update suParams) { + return Observable.fromCallable(() -> slotUpdate(slot, suParams)); + } + } +} \ No newline at end of file diff --git a/src/main/bookingbugAPI/api/AdminURLS.java b/src/main/bookingbugAPI2/api/AdminURLS.java similarity index 83% rename from src/main/bookingbugAPI/api/AdminURLS.java rename to src/main/bookingbugAPI2/api/AdminURLS.java index f34da2b..87f9e9b 100644 --- a/src/main/bookingbugAPI/api/AdminURLS.java +++ b/src/main/bookingbugAPI2/api/AdminURLS.java @@ -1,15 +1,52 @@ -package bookingbugAPI.api; +package bookingbugAPI2.api; +import bookingbugAPI2.services.ServiceProvider; import com.damnhandy.uri.template.UriTemplate; import com.damnhandy.uri.template.UriTemplateBuilder; -import helpers.Config; - +import helpers2.Config; +//TODO: Fix URLS (refactor to be same with Login) public class AdminURLS { + ServiceProvider provider; + + public AdminURLS(ServiceProvider provider) { + this.provider = provider; + } + + /** + * Accessor to create an instance of {@link Login} + * + * @return Login instance + */ + public Login login() { + return new Login(); + } + + public class Login { + public UriTemplate auth() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) + .literal("/login") + .build(); + } + + public UriTemplate sso() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) + .literal("/login/sso") + .path(UriTemplateBuilder.var("companyId")) + .query(UriTemplateBuilder.var("token")) + .build(); + } + } + public static class Company { + public static UriTemplate companyRead() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + return companyRead(new Config().serverUrl); + } + + public static UriTemplate companyRead(String serverUrl) { + return UriTemplate.buildFromTemplate(serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/company") @@ -23,27 +60,28 @@ public static UriTemplate companyConfigRead() { .literal("/company_configuration") .build(); } -/* - public static UriTemplate administratorCreate() { + + } + + public static class Address { + public static UriTemplate addressList(){ return UriTemplate.buildFromTemplate(new Config().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) - .literal("/administrators") + .literal("/addresses") .build(); } -*/ - } - public static class Address { - public static UriTemplate addressList(){ + public static UriTemplate addressRead(){ return UriTemplate.buildFromTemplate(new Config().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/addresses") + .path(UriTemplateBuilder.var("addressId")) .build(); } - public static UriTemplate addressRead(){ + public static UriTemplate addressDelete() { return UriTemplate.buildFromTemplate(new Config().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) @@ -175,6 +213,16 @@ public static UriTemplate personDelete(){ .path(UriTemplateBuilder.var("personId")) .build(); } + + public static UriTemplate personReadUsingRefId() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/people") + .literal("/find_by_ref") + .path(UriTemplateBuilder.var("refId")) + .build(); + } } @@ -245,6 +293,15 @@ public static UriTemplate slotRead() { .path(UriTemplateBuilder.var("slotId")) .build(); } + + public static UriTemplate slotDelete() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("slots") + .path(UriTemplateBuilder.var("slotId")) + .build(); + } } @@ -375,26 +432,34 @@ public static UriTemplate bookingAnswerQuestion(){ } } + /** + * Accessor to create an instance of {@link Client} + * + * @return Client instance + */ + public Client client() { + return new Client(); + } - public static class Client { - public static UriTemplate clientList() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + public class Client { + public UriTemplate clientList() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/client") .build(); } - public static UriTemplate clientCreate() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + public UriTemplate clientCreate() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/client") .build(); } - public static UriTemplate clientRead() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + public UriTemplate clientRead() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/client") @@ -402,8 +467,8 @@ public static UriTemplate clientRead() { .build(); } - public static UriTemplate clientReadUsingRefId() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + public UriTemplate clientReadUsingRefId() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/client") @@ -412,8 +477,8 @@ public static UriTemplate clientReadUsingRefId() { .build(); } - public static UriTemplate clientReadUsingEmail() { - return UriTemplate.buildFromTemplate(new Config().serverUrl) + public UriTemplate clientReadUsingEmail() { + return UriTemplate.buildFromTemplate(provider.configService().serverUrl) .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/client") @@ -442,6 +507,12 @@ public static UriTemplate purchaseList() { .literal("/admin") .path(UriTemplateBuilder.var("companyId")) .literal("/purchases") + .query( + UriTemplateBuilder.var("created_from"), + UriTemplateBuilder.var("created_to"), + UriTemplateBuilder.var("admin_booking"), + UriTemplateBuilder.var("order_by"), + UriTemplateBuilder.var("order_by_reverse")) .build(); } @@ -453,6 +524,16 @@ public static UriTemplate purchaseRead() { .path(UriTemplateBuilder.var("purchaseId")) .build(); } + + public static UriTemplate purchasePay() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/purchases") + .path(UriTemplateBuilder.var("purchaseId")) + .literal("/pay") + .build(); + } } @@ -542,6 +623,24 @@ public static UriTemplate administratorRead() { .path(UriTemplateBuilder.var("adminId")) .build(); } + + public static UriTemplate administratorDelete() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/administrators") + .path(UriTemplateBuilder.var("adminId")) + .build(); + } + + public static UriTemplate administratorUpdate() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/administrators") + .path(UriTemplateBuilder.var("adminId")) + .build(); + } } @@ -581,6 +680,24 @@ public static UriTemplate scheduleRead() { .path(UriTemplateBuilder.var("scheduleId")) .build(); } + + public static UriTemplate scheduleDelete(){ + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/schedules") + .path(UriTemplateBuilder.var("scheduleId")) + .build(); + } + + public static UriTemplate scheduleUpdate() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/schedules") + .path(UriTemplateBuilder.var("scheduleId")) + .build(); + } } @@ -743,4 +860,24 @@ public static UriTemplate eventRead(){ .build(); } } + + public static class Clinic { + public static UriTemplate clinicRead() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/clinics") + .build(); + } + + public static UriTemplate clinicCancel() { + return UriTemplate.buildFromTemplate(new Config().serverUrl) + .literal("/admin") + .path(UriTemplateBuilder.var("companyId")) + .literal("/clinics") + .path(UriTemplateBuilder.var("clinicId")) + .literal("/cancel") + .build(); + } + } } diff --git a/src/main/bookingbugAPI/api/AuthedAPI.java b/src/main/bookingbugAPI2/api/AuthedAPI.java similarity index 86% rename from src/main/bookingbugAPI/api/AuthedAPI.java rename to src/main/bookingbugAPI2/api/AuthedAPI.java index a117351..03c3d26 100644 --- a/src/main/bookingbugAPI/api/AuthedAPI.java +++ b/src/main/bookingbugAPI2/api/AuthedAPI.java @@ -1,4 +1,4 @@ -package bookingbugAPI.api; +package bookingbugAPI2.api; /** * Created by sebi on 19.05.2016. diff --git a/src/main/bookingbugAPI/api/PublicURLS.java b/src/main/bookingbugAPI2/api/PublicURLS.java similarity index 99% rename from src/main/bookingbugAPI/api/PublicURLS.java rename to src/main/bookingbugAPI2/api/PublicURLS.java index 1be7644..740a54b 100644 --- a/src/main/bookingbugAPI/api/PublicURLS.java +++ b/src/main/bookingbugAPI2/api/PublicURLS.java @@ -1,8 +1,8 @@ -package bookingbugAPI.api; +package bookingbugAPI2.api; import com.damnhandy.uri.template.UriTemplate; import com.damnhandy.uri.template.UriTemplateBuilder; -import helpers.Config; +import helpers2.Config; //@SuppressWarnings("unused") //use it just to highlight TODOs - comment it back afterwards diff --git a/src/main/bookingbugAPI/models/Address.java b/src/main/bookingbugAPI2/models/Address.java similarity index 93% rename from src/main/bookingbugAPI/models/Address.java rename to src/main/bookingbugAPI2/models/Address.java index f01e559..1667590 100644 --- a/src/main/bookingbugAPI/models/Address.java +++ b/src/main/bookingbugAPI2/models/Address.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Address extends BBRoot{ @@ -8,7 +8,9 @@ public Address(HttpServiceResponse httpServiceResponse){ super(httpServiceResponse); } - public Address() {} + public Address(HttpServiceResponse httpServiceResponse, String auth_token) { + super(httpServiceResponse, auth_token); + } /** * Returns the id. diff --git a/src/main/bookingbugAPI/models/Administrator.java b/src/main/bookingbugAPI2/models/Administrator.java similarity index 92% rename from src/main/bookingbugAPI/models/Administrator.java rename to src/main/bookingbugAPI2/models/Administrator.java index 9bb8875..3cff15c 100644 --- a/src/main/bookingbugAPI/models/Administrator.java +++ b/src/main/bookingbugAPI2/models/Administrator.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.io.IOException; import java.net.URL; @@ -23,14 +23,14 @@ public Administrator(HttpServiceResponse httpServiceResponse) { public Company getCompany() throws IOException { String link = response.getRep().getLinkByRel("company").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new Company(HttpService.api_GET(url, auth_token), auth_token); + return new Company(PlainHttpService.api_GET(url, auth_token), auth_token); } public BBRoot getEditSchema() throws IOException { String link = response.getRep().getLinkByRel("edit").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new BBRoot(HttpService.api_GET(url, auth_token), auth_token); + return new BBRoot(PlainHttpService.api_GET(url, auth_token), auth_token); } diff --git a/src/main/bookingbugAPI/models/Answer.java b/src/main/bookingbugAPI2/models/Answer.java similarity index 97% rename from src/main/bookingbugAPI/models/Answer.java rename to src/main/bookingbugAPI2/models/Answer.java index 6a1e197..53ff891 100644 --- a/src/main/bookingbugAPI/models/Answer.java +++ b/src/main/bookingbugAPI2/models/Answer.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Answer extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/BBCollection.java b/src/main/bookingbugAPI2/models/BBCollection.java similarity index 97% rename from src/main/bookingbugAPI/models/BBCollection.java rename to src/main/bookingbugAPI2/models/BBCollection.java index e412ed9..0f714b3 100644 --- a/src/main/bookingbugAPI/models/BBCollection.java +++ b/src/main/bookingbugAPI2/models/BBCollection.java @@ -1,7 +1,7 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.theoryinpractise.halbuilder.api.ContentRepresentation; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; diff --git a/src/main/bookingbugAPI/models/BBRoot.java b/src/main/bookingbugAPI2/models/BBRoot.java similarity index 93% rename from src/main/bookingbugAPI/models/BBRoot.java rename to src/main/bookingbugAPI2/models/BBRoot.java index cfa0e37..d9ef2a6 100644 --- a/src/main/bookingbugAPI/models/BBRoot.java +++ b/src/main/bookingbugAPI2/models/BBRoot.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.core.JsonProcessingException; @@ -12,9 +12,9 @@ import com.theoryinpractise.halbuilder.api.RepresentationException; import com.theoryinpractise.halbuilder.impl.representations.ContentBasedRepresentation; import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory; -import helpers.Config; -import helpers.HttpServiceResponse; -import helpers.hal_addon.CustomJsonDeserializer; +import helpers2.Config; +import helpers2.HttpServiceResponse; +import helpers2.hal_addon.CustomJsonDeserializer; import org.joda.time.DateTime; import java.io.*; @@ -42,7 +42,6 @@ public class BBRoot { protected HttpServiceResponse response; protected String auth_token = null; public String id; - public Map data; public int INTEGER_DEFAULT_VALUE = 0; public double DOUBLE_DEFAULT_VALUE = 0.0; public boolean BOOLEAN_DEFAULT_VALUE = false; @@ -74,7 +73,7 @@ public BBRoot() { public BBRoot getLoginSchema() throws IOException { URL url = new URL(UriTemplate.fromTemplate(response.getRep().getLinkByRel("new_login").getHref()).expand()); - HttpServiceResponse response = HttpService.api_GET(url); + HttpServiceResponse response = PlainHttpService.api_GET(url); return new BBRoot(response); } @@ -83,7 +82,7 @@ public Login auth(Map params) throws IOException { HttpServiceResponse resp; try { URL url = new URL(UriTemplate.fromTemplate(new Config().serverUrl + "/login").expand()); - resp = HttpService.api_POST(url, params); + resp = PlainHttpService.api_POST(url, params); auth_token = (String) resp.getRep().getValue("auth_token"); } catch (HttpException e) { //e.printStackTrace(); @@ -105,7 +104,7 @@ public Login auth(Map params) throws IOException { public Login auth(Map params, Link link) throws IOException { URL url = new URL(link.getHref()); - HttpServiceResponse resp = HttpService.api_POST(url, params); + HttpServiceResponse resp = PlainHttpService.api_POST(url, params); auth_token = (String) resp.getRep().getValue("auth_token"); return new Login(resp); } @@ -219,7 +218,7 @@ public String getLink(String rel) { String link = null; try { link = response.getRep().getLinkByRel(rel).getHref(); - } catch (RepresentationException e) { + } catch (RepresentationException | NullPointerException e) { //e.printStackTrace(); } return link; @@ -252,9 +251,9 @@ public String toString() { } public String toPrettyString() { - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = CustomJsonDeserializer.getMapper(); try { - return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response.getRep()); + return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(response); } catch (JsonProcessingException e) { e.printStackTrace(); return toString(); diff --git a/src/main/bookingbugAPI/models/Basket.java b/src/main/bookingbugAPI2/models/Basket.java similarity index 95% rename from src/main/bookingbugAPI/models/Basket.java rename to src/main/bookingbugAPI2/models/Basket.java index 58f70b9..7ac70ca 100644 --- a/src/main/bookingbugAPI/models/Basket.java +++ b/src/main/bookingbugAPI2/models/Basket.java @@ -1,8 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; - -import java.util.List; +import helpers2.HttpServiceResponse; public class Basket extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/BasketItem.java b/src/main/bookingbugAPI2/models/BasketItem.java similarity index 96% rename from src/main/bookingbugAPI/models/BasketItem.java rename to src/main/bookingbugAPI2/models/BasketItem.java index bf837c0..97602c7 100644 --- a/src/main/bookingbugAPI/models/BasketItem.java +++ b/src/main/bookingbugAPI2/models/BasketItem.java @@ -1,13 +1,10 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.PublicURLS; -import bookingbugAPI.services.HttpService; import com.theoryinpractise.halbuilder.api.ContentRepresentation; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; import java.io.IOException; -import java.net.URL; import java.util.List; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/BasketItemSettings.java b/src/main/bookingbugAPI2/models/BasketItemSettings.java similarity index 93% rename from src/main/bookingbugAPI/models/BasketItemSettings.java rename to src/main/bookingbugAPI2/models/BasketItemSettings.java index 038c9d4..9fb79b8 100644 --- a/src/main/bookingbugAPI/models/BasketItemSettings.java +++ b/src/main/bookingbugAPI2/models/BasketItemSettings.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; /** diff --git a/src/main/bookingbugAPI/models/BookableAvailability.java b/src/main/bookingbugAPI2/models/BookableAvailability.java similarity index 93% rename from src/main/bookingbugAPI/models/BookableAvailability.java rename to src/main/bookingbugAPI2/models/BookableAvailability.java index 7879c42..0f89462 100644 --- a/src/main/bookingbugAPI/models/BookableAvailability.java +++ b/src/main/bookingbugAPI2/models/BookableAvailability.java @@ -1,13 +1,11 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.theoryinpractise.halbuilder.api.ContentRepresentation; import com.theoryinpractise.halbuilder.api.ReadableRepresentation; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.text.ParseException; import java.util.ArrayList; -import java.util.Calendar; import java.util.Date; /** diff --git a/src/main/bookingbugAPI/models/BookableItem.java b/src/main/bookingbugAPI2/models/BookableItem.java similarity index 83% rename from src/main/bookingbugAPI/models/BookableItem.java rename to src/main/bookingbugAPI2/models/BookableItem.java index ca3cf7a..b0634a8 100644 --- a/src/main/bookingbugAPI/models/BookableItem.java +++ b/src/main/bookingbugAPI2/models/BookableItem.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class BookableItem extends BBRoot { diff --git a/src/main/bookingbugAPI/models/Booking.java b/src/main/bookingbugAPI2/models/Booking.java similarity index 88% rename from src/main/bookingbugAPI/models/Booking.java rename to src/main/bookingbugAPI2/models/Booking.java index 3c2980a..034a715 100644 --- a/src/main/bookingbugAPI/models/Booking.java +++ b/src/main/bookingbugAPI2/models/Booking.java @@ -1,17 +1,15 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.AdminURLS; -import bookingbugAPI.models.params.BookingCancelParams; -import bookingbugAPI.models.params.BookingUpdateParams; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.api.AdminURLS; +import bookingbugAPI2.models.params.BookingCancelParams; +import bookingbugAPI2.models.params.BookingUpdateParams; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; -import com.j256.ormlite.stmt.query.In; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; import java.io.IOException; import java.net.URL; -import java.util.List; import java.util.Map; @@ -25,37 +23,6 @@ public Booking(HttpServiceResponse response) { super(response); } - public Booking() { - } - - public BBRoot getSchema() throws IOException { - String link = getRep().getLinkByRel("edit").getHref(); - URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new BBRoot(HttpService.api_GET(url, auth_token)); - } - - /** - * Returns a new Booking - update the current booking with provided params - * - * @param bParams - * @throws IOException - */ - public Booking bookingUpdate_Admin(BookingUpdateParams bParams) throws IOException { - URL url = new URL(AdminURLS.Bookings.bookingUpdate().set("companyId", getCompanyId()).set("id", this.id).expand()); - return new Booking(HttpService.api_PUT(url, bParams.getParams(), auth_token), auth_token); - } - - /** - * Deletes the booking - * - * @param bcParams - * @return - * @throws IOException - */ - public Booking bookingCancel_Admin(BookingCancelParams bcParams) throws IOException { - URL url = new URL(AdminURLS.Bookings.bookingCancel().set("companyId", getCompanyId()).set("id", this.id).expand()); - return new Booking(HttpService.api_DELETE(url, HttpService.jsonContentType, bcParams.getParams(), auth_token), auth_token); - } /** * Returns the booking id. diff --git a/src/main/bookingbugAPI/models/BookingQuestion.java b/src/main/bookingbugAPI2/models/BookingQuestion.java similarity index 83% rename from src/main/bookingbugAPI/models/BookingQuestion.java rename to src/main/bookingbugAPI2/models/BookingQuestion.java index fdbf525..142c2f3 100644 --- a/src/main/bookingbugAPI/models/BookingQuestion.java +++ b/src/main/bookingbugAPI2/models/BookingQuestion.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class BookingQuestion extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/Category.java b/src/main/bookingbugAPI2/models/Category.java similarity index 92% rename from src/main/bookingbugAPI/models/Category.java rename to src/main/bookingbugAPI2/models/Category.java index fbc95ea..cfe6ff7 100644 --- a/src/main/bookingbugAPI/models/Category.java +++ b/src/main/bookingbugAPI2/models/Category.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Category extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/Client.java b/src/main/bookingbugAPI2/models/Client.java similarity index 98% rename from src/main/bookingbugAPI/models/Client.java rename to src/main/bookingbugAPI2/models/Client.java index 5b04f17..5eeaa44 100644 --- a/src/main/bookingbugAPI/models/Client.java +++ b/src/main/bookingbugAPI2/models/Client.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.util.List; import java.util.Map; diff --git a/src/main/bookingbugAPI2/models/Clinic.java b/src/main/bookingbugAPI2/models/Clinic.java new file mode 100644 index 0000000..ffedc8d --- /dev/null +++ b/src/main/bookingbugAPI2/models/Clinic.java @@ -0,0 +1,61 @@ +package bookingbugAPI2.models; + +import helpers2.HttpServiceResponse; +import org.joda.time.DateTime; + +import java.util.List; + + +public class Clinic extends BBRoot{ + public Clinic(HttpServiceResponse httpServiceResponse) { + super(httpServiceResponse); + } + + /** + * Returns the name of the clinic. + * @return the name of the clinic associated with the current Clinic object. + */ + public String getName() { + return get("name"); + } + + /** + * Returns the starting time with {@link DateTime DateTime()} as format. + * @return the starting time associated with the current Clinic object. + */ + public DateTime getStartTime() { + return getDate("start_time"); + } + + /** + * Returns the ending time with {@link DateTime DateTime()} as format. + * @return the ending time associated with the current Clinic object. + */ + public DateTime getEndTime() { + return getDate("end_time"); + } + + /** + * Returns the resource ids. + * @return the resource ids associated with the current Clinic object. + */ + public List getResourceIds() { + return getStringArray("resource_ids"); + } + + /** + * Returns the person ids. + * @return the person ids associated with the current Clinic object. + */ + public List getPersonIds() { + return getStringArray("person_ids"); + } + + /** + * Returns the service ids. + * @return the service ids associated with the current Clinic object. + */ + public List getServiceIds() { + return getStringArray("service_ids"); + } +} diff --git a/src/main/bookingbugAPI/models/Company.java b/src/main/bookingbugAPI2/models/Company.java similarity index 77% rename from src/main/bookingbugAPI/models/Company.java rename to src/main/bookingbugAPI2/models/Company.java index 82059e4..f17e88e 100644 --- a/src/main/bookingbugAPI/models/Company.java +++ b/src/main/bookingbugAPI2/models/Company.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.AdminURLS; -import bookingbugAPI.api.PublicURLS; -import bookingbugAPI.models.params.*; +import bookingbugAPI2.api.AdminURLS; +import bookingbugAPI2.api.PublicURLS; +import bookingbugAPI2.models.params.*; import com.damnhandy.uri.template.UriTemplate; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -10,12 +10,11 @@ import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.module.jsonSchema.JsonSchema; import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; -import com.j256.ormlite.stmt.query.In; import com.theoryinpractise.halbuilder.api.ContentRepresentation; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import java.io.*; import java.net.MalformedURLException; @@ -24,25 +23,26 @@ import static com.theoryinpractise.halbuilder.api.RepresentationFactory.HAL_JSON; -public class Company extends BBRoot{ +public class Company extends BBRoot { private Service servicesList; private Administrator administratorList; private BBRoot administratorSchema; - public Company(HttpServiceResponse httpServiceResponse){ + public Company(HttpServiceResponse httpServiceResponse) { super(httpServiceResponse); } - public Company(HttpServiceResponse httpServiceResponse, String auth_token){ + public Company(HttpServiceResponse httpServiceResponse, String auth_token) { super(httpServiceResponse); this.auth_token = auth_token; } - public Company() {} + public Company() { + } /* @@ -70,18 +70,20 @@ public Service getServicesList() throws IOException { /** * Load All of the Links and Properties of a Company + * * @return CompanyConfig * @throws IOException */ public CompanyConfig companyRead_Admin() throws IOException { - URL url = new URL (AdminURLS.Company.companyConfigRead().set("companyId", this.id).expand()); - BBCollection config = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "config", CompanyConfig.class); + URL url = new URL(AdminURLS.Company.companyConfigRead().set("companyId", this.id).expand()); + BBCollection config = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "config", CompanyConfig.class); return config.getObjectAtIndex(0); } /** * Get the Bookable Items Based on Another Item + * * @param bilParams * @return BBCollection * @throws IOException @@ -89,39 +91,41 @@ public CompanyConfig companyRead_Admin() throws IOException { public BBCollection bookableItemsList_Admin(BookableItemListParams bilParams) throws IOException { String urlStr = AdminURLS.BookableItem.bookableItemList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, bilParams.getParams())); - BBCollection bookableItems = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "bookable_items", BookableItem.class); + BBCollection bookableItems = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "bookable_items", BookableItem.class); return bookableItems; } /** * Get All Bookable Services + * * @return BBCollection * @throws IOException */ public BBCollection serviceList() throws IOException { URL url = new URL(PublicURLS.Service.serviceList().set("companyId", this.id).expand()); - BBCollection services = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "services", Service.class); + BBCollection services = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "services", Service.class); return services; } public Service serviceNew_Admin() throws IOException { URL url = new URL(AdminURLS.Service.serviceNew().set("companyId", this.id).expand()); - BBCollection services = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "service", Service.class); + BBCollection services = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "service", Service.class); return services.getObjectAtIndex(0); } public Service serviceEdit_Admin(String serviceId) throws IOException { URL url = new URL(AdminURLS.Service.serviceEdit().set("companyId", this.id).set("serviceId", serviceId).expand()); - BBCollection services = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "service", Service.class); + BBCollection services = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "service", Service.class); return services.getObjectAtIndex(0); } /** * List of Services for a Company. + * * @return BBCollection * @throws IOException */ @@ -130,86 +134,91 @@ public BBCollection serviceList_Admin(ServiceListParams slParams) throw AdminURLS.Service.serviceList().set("companyId", this.id), slParams); URL url = new URL(template.expand()); - BBCollection services = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "services", Service.class); + BBCollection services = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "services", Service.class); return services; } /** * Get a Specific Service. + * * @param serviceId Service Id * @return Service * @throws IOException */ public Service serviceRead(String serviceId) throws IOException { URL url = new URL(PublicURLS.Service.serviceRead().set("companyId", this.id).set("serviceId", serviceId).expand()); - BBCollection services = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "service", Service.class); + BBCollection services = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "service", Service.class); return services.getObjectAtIndex(0); } /** * Load a Specific Service Details + * * @param serviceId * @return Service * @throws IOException */ public Service serviceRead_Admin(String serviceId) throws IOException { URL url = new URL(AdminURLS.Service.serviceRead().set("companyId", this.id).set("serviceId", serviceId).expand()); - BBCollection service = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "service", Service.class); + BBCollection service = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "service", Service.class); return service.getObjectAtIndex(0); } //TODO: kept for compatibility with AdminController until checked there - public People getPeopleList() throws IOException { + public Person getPeopleList() throws IOException { String link = response.getRep().getLinkByRel("people").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new People(HttpService.api_GET(url, auth_token), auth_token); + return new Person(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Get All Bookable People for a Company. + * * @return BBCollection * @throws IOException */ - public BBCollection personList() throws IOException { + public BBCollection personList() throws IOException { URL url = new URL(PublicURLS.Person.personList().set("companyId", this.id).expand()); - BBCollection people = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "people", People.class); + BBCollection people = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "people", Person.class); return people; } - public BBCollection personList_Admin(PeopleListParams plParams) throws IOException { + public BBCollection personList_Admin(PersonListParams plParams) throws IOException { String urlStr = AdminURLS.Person.personList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, plParams.getParams())); - BBCollection people = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "people", People.class); + BBCollection people = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "people", Person.class); return people; } /** * Get a Specific Bookable Person’s Details. + * * @param personId Person Id * @return People * @throws IOException */ - public People personRead(String personId) throws IOException { + public Person personRead(String personId) throws IOException { URL url = new URL(PublicURLS.Person.personRead().set("companyId", this.id).set("personId", personId).expand()); - BBCollection people = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "person", People.class); + BBCollection people = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "person", Person.class); return people.getObjectAtIndex(0); } /** * Get a Specific Person Details using a Reference ID + * * @return People * @throws IOException */ - public People personReadUsingReferenceId(String ref) throws IOException { + public Person personReadUsingReferenceId(String ref) throws IOException { URL url = new URL(PublicURLS.Person.personReadUsingReferenceId().set("companyId", this.id).set("ref", ref).expand()); - BBCollection people = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "person", People.class); + BBCollection people = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "person", Person.class); return people.getObjectAtIndex(0); } @@ -217,18 +226,20 @@ public People personReadUsingReferenceId(String ref) throws IOException { /** * Get All Bookable Resources * Results are returned as a paginated list. + * * @return BBCollection * @throws IOException */ public BBCollection resourceList() throws IOException { URL url = new URL(PublicURLS.Resource.resourceList().set("companyId", this.id).expand()); - BBCollection resources = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); + BBCollection resources = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); return resources; } /** * Get All Questions for a Company + * * @param qlParams * @return BBCollection * @throws IOException @@ -236,13 +247,14 @@ public BBCollection resourceList() throws IOException { public BBCollection questionList_Admin(QuestionListParams qlParams) throws IOException { String urlStr = AdminURLS.Question.questionList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, qlParams.getParams())); - BBCollection questions = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "questions", Question.class); + BBCollection questions = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "questions", Question.class); return questions; } /** * resourceList_Admin + * * @param rlParams * @return BBCollection * @throws IOException @@ -250,39 +262,42 @@ public BBCollection questionList_Admin(QuestionListParams qlParams) th public BBCollection resourceList_Admin(ResourceListParams rlParams) throws IOException { String urlStr = AdminURLS.Resource.resourceList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, rlParams.getParams())); - BBCollection resources = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); + BBCollection resources = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); return resources; } /** * Get a Specific Bookable Resource + * * @param resourceId Resource Id * @return Resource * @throws IOException */ public Resource resourceRead(String resourceId) throws IOException { URL url = new URL(PublicURLS.Resource.resourceRead().set("companyId", this.id).set("resourceId", resourceId).expand()); - BBCollection resource = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); + BBCollection resource = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); return resource.getObjectAtIndex(0); } /** * Load a Specific Resource Details + * * @param resourceId * @return Resource * @throws IOException */ public Resource resourceRead_Admin(String resourceId) throws IOException { URL url = new URL(AdminURLS.Resource.resourceRead().set("companyId", this.id).set("resourceId", resourceId).expand()); - BBCollection resource = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); + BBCollection resource = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "resources", Resource.class); return resource.getObjectAtIndex(0); } /** * Search for a Range of Calendar Bookings for a Business. + * * @param slParams SlotListParams * @return BBCollection * @throws IOException @@ -290,38 +305,41 @@ public Resource resourceRead_Admin(String resourceId) throws IOException { public BBCollection slotList_Admin(SlotListParams slParams) throws IOException { String urlStr = AdminURLS.Slot.slotList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, slParams.getParams())); - BBCollection slots = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "slots", Slot.class); + BBCollection slots = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "slots", Slot.class); return slots; } /** * Get the Details and Links of a Specific Booked Slot + * * @param slotId * @return Slot * @throws IOException */ public Slot slotRead_Admin(String slotId) throws IOException { URL url = new URL(AdminURLS.Slot.slotRead().set("companyId", this.id).set("slotId", slotId).expand()); - BBCollection slots = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "slots", Slot.class); + BBCollection slots = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "slots", Slot.class); return slots.getObjectAtIndex(0); } /** * Load All of the Links and Properties of a Company + * * @param companyId Company Id * @return Resource * @throws IOException */ public Resource companyDetails(String companyId) throws IOException { URL url = new URL(PublicURLS.Details.companyDetails().set("companyId", companyId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Get a List of Bookable Events. + * * @return BBCollection * @throws IOException */ @@ -331,6 +349,7 @@ public BBCollection eventList() throws IOException { /** * Get a List of Bookable Events. + * * @param params Parameters for pagination * @return BBCollection * @throws IOException @@ -340,48 +359,52 @@ public BBCollection eventList(Params params) throws IOException { PublicURLS.Event.eventList().set("companyId", this.id), params); URL url = new URL(template.expand()); - return new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "events", Event.class); + return new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "events", Event.class); } /** * Get a Specific Event. + * * @return Event * @throws IOException */ public Event eventRead(String eventId) throws IOException { URL url = new URL(PublicURLS.Event.eventRead().set("companyId", this.id).set("eventId", eventId).expand()); - BBCollection events = new BBCollection(HttpService.api_GET(url), auth_token, "events", Event.class); + BBCollection events = new BBCollection(PlainHttpService.api_GET(url), auth_token, "events", Event.class); return events.getObjectAtIndex(0); } /** * Get the Bookable Items Based on Another Item + * * @return BBCollection * @throws IOException */ public BBCollection bookableItemsList() throws IOException { URL url = new URL(PublicURLS.Bookable.bookableItemsList().set("companyId", this.id).expand()); - BBCollection bookableItems = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "items", BookableItem.class); + BBCollection bookableItems = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "items", BookableItem.class); return bookableItems; } /** * This loads a list of bookable items for a particular date + * * @return BBCollection * @throws IOException */ public BBCollection bookableItemsByDate(String date) throws IOException { URL url = new URL(PublicURLS.Bookable.bookableItemsByDate().set("companyId", this.id).set("date", date).expand()); - BBCollection bookableItems = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "bookable_items_by_date", BookableItem.class); + BBCollection bookableItems = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "bookable_items_by_date", BookableItem.class); return bookableItems; } /** * Get Data for a range of Days + * * @return Resource * @throws IOException */ @@ -389,14 +412,15 @@ public BBRoot availabilityDaysForBookableItem(TimeDataParams params) throws IOEx URL url = new URL( PublicURLS.Bookable.availabilityDaysForBookableItem() .set("companyId", this.id) - .set((Map)params.getParams()) + .set((Map) params.getParams()) .expand()); - return new BBRoot(HttpService.api_GET(url, auth_token), auth_token); + return new BBRoot(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Get Data for availabile times for a day + * * @return Resource * @throws IOException */ @@ -404,42 +428,45 @@ public BBCollection availabilityTimesForBookableItem(TimeD URL url = new URL( PublicURLS.Bookable.availabilityTimesForBookableItem() .set("companyId", this.id) - .set((Map)params.getParams()) + .set((Map) params.getParams()) .expand()); - return new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "events", BookableAvailability.class); + return new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "events", BookableAvailability.class); } /** * Check if available + * * @return Resource * @throws IOException */ public Resource availabilityCheck(String dateTime) throws IOException { URL url = new URL(PublicURLS.Bookable.availabilityCheck().set("companyId", this.id).set("dateTime", dateTime).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Details about how a client should book + * * @return Resource * @throws IOException */ public Resource memberBookingDetails() throws IOException { URL url = new URL(PublicURLS.Bookable.memberBookingDetails().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Get All Event Groups. + * * @return BBCollection * @throws IOException */ public BBCollection eventGroupList() throws IOException { URL url = new URL(PublicURLS.EventGroup.eventGroupList().set("companyId", this.id).expand()); - BBCollection eventGroups = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "event_groups", EventGroup.class); + BBCollection eventGroups = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "event_groups", EventGroup.class); eventGroups.setCollectionNameSpace(""); return eventGroups; } @@ -447,18 +474,20 @@ public BBCollection eventGroupList() throws IOException { /** * Get a Specific Event Group. + * * @return EventGroup * @throws IOException */ public EventGroup eventGroupRead(String eventGroupId) throws IOException { - URL url = new URL (PublicURLS.EventGroup.eventGroupRead().set("companyId", this.id).set("serviceId", eventGroupId).expand()); - BBCollection eventGroups = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "event_group", EventGroup.class); + URL url = new URL(PublicURLS.EventGroup.eventGroupRead().set("companyId", this.id).set("serviceId", eventGroupId).expand()); + BBCollection eventGroups = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "event_group", EventGroup.class); return eventGroups.getObjectAtIndex(0); } /** * Get a List of Courses or Repeating Events for a Company. + * * @return BBCollection * @throws IOException */ @@ -468,6 +497,7 @@ public BBCollection eventChainList() throws IOException { /** * Get a List of Courses or Repeating Events for a Company. + * * @param params Parameters for pagination * @return BBCollection * @throws IOException @@ -477,19 +507,20 @@ public BBCollection eventChainList(Params params) throws IOException AdminURLS.EventChain.eventChainList().set("companyId", this.id), params); URL url = new URL(template.expand()); - BBCollection eventChains = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "event_chains", EventChain.class); + BBCollection eventChains = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "event_chains", EventChain.class); return eventChains; } /** * Get a Specific Event Chain. + * * @return EventChain * @throws IOException */ public EventChain eventChainRead(String eventChainId) throws IOException { - URL url = new URL (PublicURLS.EventChain.eventChainRead().set("companyId", this.id).set("eventChainId", eventChainId).expand()); - BBCollection eventChains = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "event_chain", EventChain.class); + URL url = new URL(PublicURLS.EventChain.eventChainRead().set("companyId", this.id).set("eventChainId", eventChainId).expand()); + BBCollection eventChains = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "event_chain", EventChain.class); return eventChains.getObjectAtIndex(0); } @@ -497,50 +528,54 @@ public EventChain eventChainRead(String eventChainId) throws IOException { /** * Get All Questions for a Company. *
Results are returned as a group of question for a specific question group. + * * @return BBCollection * @throws IOException */ public BBCollection bookingQuestionList(String detailGroupId) throws IOException { URL url = new URL(PublicURLS.BookingQuestion.bookingQuestionList().set("companyId", this.id).set("detailGroupId", detailGroupId).expand()); - BBCollection bokingQuestions = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "booking_questions", BookingQuestion.class); + BBCollection bokingQuestions = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "booking_questions", BookingQuestion.class); return bokingQuestions; } /** * Question Read + * * @param questionId Question Id * @return BookingQuestion * @throws IOException */ public BookingQuestion bookingQuestionRead(String questionId) throws IOException { URL url = new URL(PublicURLS.BookingQuestion.bookingQuestionRead().set("companyId", this.id).set("questionId", questionId).expand()); - BBCollection bokingQuestions = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "booking_question", BookingQuestion.class); + BBCollection bokingQuestions = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "booking_question", BookingQuestion.class); return bokingQuestions.getObjectAtIndex(0); } /** * Get all Survey Questions for a Service + * * @param detail_group_id Question Group Id * @return BBCollection * @throws IOException */ public BBCollection surveyQuestionList(String detail_group_id) throws IOException { URL url = new URL(PublicURLS.SurveyQuestion.surveyQuestionList().set("companyId", this.id).set("detail_group_id", detail_group_id).expand()); - BBCollection surveyQuestions = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "survey_questions", SurveyQuestion.class); + BBCollection surveyQuestions = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "survey_questions", SurveyQuestion.class); return surveyQuestions; } /** * List of Categories for a Company. + * * @return BBCollection * @throws IOException */ public BBCollection categoryList() throws IOException { URL url = new URL(PublicURLS.Category.categoryList().set("companyId", this.id).expand()); - BBCollection categories = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "survey_question", Category.class); + BBCollection categories = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "survey_question", Category.class); categories.setCollectionNameSpace("categories"); return categories; } @@ -548,73 +583,79 @@ public BBCollection categoryList() throws IOException { /** * Load a Specific Category Details + * * @param categoryId Category Id * @return Category * @throws IOException */ public Category categoryRead(String categoryId) throws IOException { URL url = new URL(PublicURLS.Category.categoryRead().set("companyId", this.id).set("categoryId", categoryId).expand()); - BBCollection categories = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "categories", Category.class); - return (Category)categories.getObjectAtIndex(0); + BBCollection categories = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "categories", Category.class); + return (Category) categories.getObjectAtIndex(0); } /** * List of Categories for a Company + * * @return Resource * @throws IOException */ public Resource categoryNamedList() throws IOException { URL url = new URL(PublicURLS.Category.categoryNamedList().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Create a new client for a business + * * @return Resource * @throws IOException */ public Resource createClient() throws IOException { URL url = new URL(PublicURLS.Client.createClient().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Update a client. + * * @param clientId * @return Resource * @throws IOException */ public Resource updateClient(String clientId) throws IOException { URL url = new URL(PublicURLS.Client.updateClient().set("companyId", this.id).set("clientId", clientId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Search for a client by email against the company that you are currently logged in as + * * @param email Email * @return Resource * @throws IOException */ public Client findByEmail(String email) throws IOException { URL url = new URL(PublicURLS.Client.findByEmail().set("companyId", this.id).set("email", email).expand()); - BBCollection clients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); + BBCollection clients = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); return clients.getObjectAtIndex(0); } /** * Get all the child clients of a particular client + * * @param clientId Client Id * @return Resource * @throws IOException */ public BBCollection childClientsRead(String clientId) throws IOException { URL url = new URL(PublicURLS.Client.readChildClients().set("companyId", this.id).set("clientId", clientId).expand()); - BBCollection childClients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); + BBCollection childClients = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); childClients.setCollectionNameSpace("child_clients"); return childClients; } @@ -622,41 +663,43 @@ public BBCollection childClientsRead(String clientId) throws IOException /** * Get All Custom Booking Text for a Company + * * @return * @throws IOException */ public Resource bookingTextList() throws IOException { URL url = new URL(PublicURLS.BookingText.getBookingText().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } /** * Get all possible Space Statuses for a Company + * * @return Resource * @throws IOException */ public Resource spaceStatusList() throws IOException { URL url = new URL(PublicURLS.Company.spaceStatusList().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url)); + return new Resource(PlainHttpService.api_GET(url)); } - /** * Loads all of the public settings for a company, this allows you to configure a booking widget, * and shows all of the details need to book and show an appropriate widget. + * * @return CompanySettings * @throws IOException */ public CompanySettings getSettings() throws IOException { - if(getRep().getResourcesByRel("settings").size() > 0) { + if (getRep().getResourcesByRel("settings").size() > 0) { //Return settings from embedded return new CompanySettings(new HttpServiceResponse((ContentRepresentation) getRep().getResourcesByRel("settings").get(0))); } else { //Call API URL url = new URL(PublicURLS.Company.settingsDetails().set("companyId", this.id).expand()); - return new CompanySettings(HttpService.api_GET(url)); + return new CompanySettings(PlainHttpService.api_GET(url)); } } @@ -664,12 +707,13 @@ public CompanySettings getSettings() throws IOException { * You can either get all the company questions or pass a param to specifiy that you only want company questions * that apply to either a service, resource, person, company: *
Service = 1, Resource = 2, Person = 3, Company = 4. + * * @return Resource * @throws IOException */ public Resource businessQuestions() throws IOException { URL url = new URL(PublicURLS.Company.businessQuestions().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url)); + return new Resource(PlainHttpService.api_GET(url)); } @@ -678,18 +722,20 @@ public Resource businessQuestions() throws IOException { *
Provide a company id to retrieve a list of addresses associated with that company. * This is a list of company branch/store/resource addresses, not client addresses. * Results are returned as a paginated list. + * * @return Resource * @throws IOException */ public BBCollection
addressList() throws IOException { URL url = new URL(PublicURLS.Address.addressList().set("companyId", this.id).expand()); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url), auth_token, "addresses", Address.class); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url), auth_token, "addresses", Address.class); return addresses; } /** * Get All Addresses for a Company. + * * @param alParams AddressListParams * @return BBCollection
* @throws IOException @@ -697,7 +743,7 @@ public BBCollection
addressList() throws IOException { public BBCollection
addressList_Admin(AddressListParams alParams) throws IOException { String urlStr = AdminURLS.Address.addressList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, alParams.getParams())); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); return addresses; } @@ -705,26 +751,28 @@ public BBCollection
addressList_Admin(AddressListParams alParams) throw /** * Get a Specific Address. *
Provide a company id and address id to retrieve the details and links of that branch/store/resource address. + * * @param addressId Address Id * @return Resource * @throws IOException */ public Address addressRead(String addressId) throws IOException { - URL url = new URL (AdminURLS.Address.addressRead().set("companyId", this.id).set("addressId", addressId).expand()); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url, auth_token), auth_token, "address", Address.class); + URL url = new URL(AdminURLS.Address.addressRead().set("companyId", this.id).set("addressId", addressId).expand()); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url, auth_token), auth_token, "address", Address.class); return addresses.getObjectAtIndex(0); } public Address addressRead_Admin(String addressId) throws IOException { - URL url = new URL (AdminURLS.Address.addressRead().set("companyId", this.id).set("id", addressId).expand()); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url, auth_token), auth_token, "address", Address.class); + URL url = new URL(AdminURLS.Address.addressRead().set("companyId", this.id).set("id", addressId).expand()); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url, auth_token), auth_token, "address", Address.class); return addresses.getObjectAtIndex(0); } /** * Sessions. Results are returned as a paginated list. + * * @param slParams * @return BBCollection * @throws IOException @@ -732,40 +780,42 @@ public Address addressRead_Admin(String addressId) throws IOException { public BBCollection sessionList_Admin(SessionListParams slParams) throws IOException { String urlStr = AdminURLS.Session.sessionList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, slParams.getParams())); - BBCollection sessions = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "sessions", Session.class); + BBCollection sessions = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "sessions", Session.class); return sessions; } public Session sessionRead_Admin(String sessionId) throws IOException { - URL url = new URL (AdminURLS.Session.sessionRead().set("companyId", this.id).set("sessionId", sessionId).expand()); - BBCollection session = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "session", Session.class); + URL url = new URL(AdminURLS.Session.sessionRead().set("companyId", this.id).set("sessionId", sessionId).expand()); + BBCollection session = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "session", Session.class); return session.getObjectAtIndex(0); } /** * Get the address result for a particular customer + * * @param customerId Customer Id * @return Resource * @throws IOException */ public Address customerAddress(String customerId) throws IOException { URL url = new URL(PublicURLS.Address.customerAddress().set("companyId", this.id).set("customerId", customerId).expand()); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); return addresses.getObjectAtIndex(0); } /** * Get a list of possible addresses from a postcode + * * @param postcode Postcode * @return Resource * @throws IOException */ public BBCollection
postCodeAddress(String postcode) throws IOException { URL url = new URL(PublicURLS.Address.postCodeAddress().set("companyId", this.id).set("postcode", postcode).expand()); - BBCollection
addresses = new BBCollection
(HttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); + BBCollection
addresses = new BBCollection
(PlainHttpService.api_GET(url, auth_token), auth_token, "addresses", Address.class); addresses.setCollectionNameSpace("address"); return addresses; } @@ -773,449 +823,389 @@ public BBCollection
postCodeAddress(String postcode) throws IOException /** * Get all Products for a Company + * * @return Resource * @throws IOException */ public BBCollection productsList() throws IOException { URL url = new URL(PublicURLS.Products.productsList().set("companyId", this.id).expand()); - BBCollection products = new BBCollection(HttpService.api_GET(url), auth_token, "products", Product.class); + BBCollection products = new BBCollection(PlainHttpService.api_GET(url), auth_token, "products", Product.class); return products; } /** * Get a specific Product + * * @param productId Product Id * @return Resource * @throws IOException */ public Product productsRead(String productId) throws IOException { - URL url = new URL (PublicURLS.Products.productRead().set("companyId", this.id).set("productId", productId).expand()); - BBCollection products = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "product", Product.class); + URL url = new URL(PublicURLS.Products.productRead().set("companyId", this.id).set("productId", productId).expand()); + BBCollection products = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "product", Product.class); return products.getObjectAtIndex(0); } /** * Slot List + * * @return Resource * @throws IOException */ public BBCollection slotList() throws IOException { URL url = new URL(PublicURLS.Slot.slotList().set("companyId", this.id).expand()); - BBCollection slots = new BBCollection(HttpService.api_GET(url), auth_token, "slots", Slot.class); + BBCollection slots = new BBCollection(PlainHttpService.api_GET(url), auth_token, "slots", Slot.class); return slots; } /** * Slot Read + * * @param slotId Slot Id * @return Resource * @throws IOException */ public Slot slotRead(String slotId) throws IOException { URL url = new URL(PublicURLS.Slot.slotRead().set("companyId", this.id).set("slotId", slotId).expand()); - BBCollection slots = new BBCollection(HttpService.api_GET(url), auth_token, "slot", Slot.class); + BBCollection slots = new BBCollection(PlainHttpService.api_GET(url), auth_token, "slot", Slot.class); return slots.getObjectAtIndex(0); } /** * Get a list of images attached to an event group. + * * @param eventGroupId Event Group Id * @return Resource * @throws IOException */ public Resource eventGroupImagesList(String eventGroupId) throws IOException { URL url = new URL(PublicURLS.EventGroupImages.eventGroupImagesList().set("companyId", this.id).set("eventGroupId", eventGroupId).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * TODO: ??? + * * @param eventGroupId Event Group Id - * @param id Id + * @param id Id * @return * @throws IOException */ public Resource eventGroupImages_f(String eventGroupId, String id) throws IOException { URL url = new URL(PublicURLS.EventGroupImages.eventGroupImages_f().set("companyId", this.id).set("eventGroupId", eventGroupId).set("id", id).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Get all the deals for a Company + * * @return Resource * @throws IOException */ public Resource dealList() throws IOException { URL url = new URL(PublicURLS.Deal.dealList().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Get all the deals for a Company. + * * @return BBCollection * @throws IOException */ public BBCollection dealList_Admin() throws IOException { - URL url = new URL (AdminURLS.Deal.dealList().set("companyId", this.id).expand()); - BBCollection deals = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "deals", Deal.class); + URL url = new URL(AdminURLS.Deal.dealList().set("companyId", this.id).expand()); + BBCollection deals = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "deals", Deal.class); return deals; } /** * Get the deal from a company using the reference id. + * * @param referenceId * @return Deal * @throws IOException */ public Deal dealReadByRef_Admin(String referenceId) throws IOException { - URL url = new URL (AdminURLS.Deal.dealReadByRef().set("companyId", this.id).set("referenceId", referenceId).expand()); - BBCollection deals = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "deal", Deal.class); + URL url = new URL(AdminURLS.Deal.dealReadByRef().set("companyId", this.id).set("referenceId", referenceId).expand()); + BBCollection deals = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "deal", Deal.class); return deals.getObjectAtIndex(0); } /** * List all the deals codes for a deal + * * @param dealId * @return BBCollection * @throws IOException */ public BBCollection dealCodesList_Admin(String dealId) throws IOException { - URL url = new URL (AdminURLS.Deal.dealCodes().set("companyId", this.id).set("dealId", dealId).expand()); - BBCollection dealCodes = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "dealCodes", DealCodes.class); + URL url = new URL(AdminURLS.Deal.dealCodes().set("companyId", this.id).set("dealId", dealId).expand()); + BBCollection dealCodes = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "dealCodes", DealCodes.class); return dealCodes; } /** * Get A Deal + * * @param dealId Deal Id * @return Resource * @throws IOException */ public Resource dealRead(String dealId) throws IOException { URL url = new URL(PublicURLS.Deal.dealRead().set("companyId", this.id).set("dealId", dealId).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Get all the service groups for a Company + * * @return Resource * @throws IOException */ public Resource serviceGroupList() throws IOException { URL url = new URL(PublicURLS.ServiceGroup.serviceGroupList().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Get a Service Group + * * @param groupId Group Id * @return Resource * @throws IOException */ public Resource serviceGroupRead(String groupId) throws IOException { URL url = new URL(PublicURLS.ServiceGroup.serviceGroupRead().set("companyId", this.id).set("groupId", groupId).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Get Contents and Details of the Current Cached Basket + * * @return Resource * @throws IOException */ public Resource readBasket() throws IOException { URL url = new URL(PublicURLS.Basket.readBasket().set("companyId", this.id).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Add Shopping Item To Basket + * * @return Resource * @throws IOException */ public Resource createBasketItem() throws IOException { URL url = new URL(PublicURLS.Basket.createBasketItem().set("companyId", this.id).expand()); - return new Resource(HttpService.api_POST(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, auth_token), auth_token); } /** * Confirm and Pay for the Items in the Shopping Basket + * * @return Resource * @throws IOException */ public Resource checkoutBasket() throws IOException { URL url = new URL(PublicURLS.Basket.checkoutBasket().set("companyId", this.id).expand()); - return new Resource(HttpService.api_POST(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, auth_token), auth_token); } /** * Empty the Shopping Basket + * * @return Resource * @throws IOException */ public Resource deleteBasket() throws IOException { URL url = new URL(PublicURLS.Basket.deleteBasket().set("companyId", this.id).expand()); this.id = ""; - return new Resource(HttpService.api_DELETE(url), auth_token); + return new Resource(PlainHttpService.api_DELETE(url), auth_token); } /** * Get the Details of a Specific Item in the Shopping Basket + * * @param basketItemId Basket Item Id * @return Resource * @throws IOException */ public Resource readBasketItem(String basketItemId) throws IOException { URL url = new URL(PublicURLS.Basket.readBasketItem().set("companyId", this.id).set("basketItemId", basketItemId).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Remove an Item for the Shopping Basket + * * @param basketItemId Basket Item Id * @return Resource * @throws IOException */ public Resource deleteBasketItem(String basketItemId) throws IOException { URL url = new URL(PublicURLS.Basket.deleteBasketItem().set("companyId", this.id).set("basketItemId", basketItemId).expand()); - return new Resource(HttpService.api_DELETE(url), auth_token); + return new Resource(PlainHttpService.api_DELETE(url), auth_token); } /** * Add a new file attachment to a basket item + * * @param basketItemId Basket Item Id * @return Resource * @throws IOException */ public Resource addFileAttachmentToBasketItem(String basketItemId) throws IOException { URL url = new URL(PublicURLS.Basket.addFileAttachmentToBasketItem().set("companyId", this.id).set("basketItemId", basketItemId).expand()); - return new Resource(HttpService.api_POST(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, auth_token), auth_token); } /** * Update a file attachment for a basket item + * * @param basketItemId Basket Item Id * @return Resource * @throws IOException */ - public Resource updateFileAttachmentToBasketItem(String basketItemId, Map params) throws IOException { + public Resource updateFileAttachmentToBasketItem(String basketItemId, Map params) throws IOException { URL url = new URL(PublicURLS.Basket.updateFileAttachmentToBasketItem().set("companyId", this.id).set("basketItemId", basketItemId).expand()); - return new Resource(HttpService.api_PUT(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_PUT(url, params, auth_token), auth_token); } /** * Get a file attachment for a basket - * @param basketId Basket Id + * + * @param basketId Basket Id * @param attachmentId Attachment Id * @return * @throws IOException */ public Resource getFileAttachmentForBasketItem(String basketId, String attachmentId) throws IOException { URL url = new URL(PublicURLS.Basket.getFileAttachmentForBasketItem().set("companyId", this.id).set("basketId", basketId).set("attachmentId", attachmentId).expand()); - return new Resource(HttpService.api_GET(url), auth_token); + return new Resource(PlainHttpService.api_GET(url), auth_token); } /** * Attempt to apply a deal to a basket + * * @return Resource * @throws IOException */ public Resource applyDeal() throws IOException { URL url = new URL(PublicURLS.Basket.applyDeal().set("companyId", this.id).expand()); - return new Resource(HttpService.api_POST(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, auth_token), auth_token); } /** * Delete a coupon from a basket + * * @return Resource * @throws IOException */ - public Resource removeDeal(Map params) throws IOException { + public Resource removeDeal(Map params) throws IOException { URL url = new URL(PublicURLS.Basket.removeDeal().set("companyId", this.id).expand()); - return new Resource(HttpService.api_PUT(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_PUT(url, params, auth_token), auth_token); } /** * Attempt to apply a discount coupon to a basket + * * @return Resource * @throws IOException */ - public Resource applyBasketCoupon(Map params) throws IOException { + public Resource applyBasketCoupon(Map params) throws IOException { URL url = new URL(PublicURLS.Basket.applyBasketCoupon().set("companyId", this.id).expand()); - return new Resource(HttpService.api_POST(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, params, auth_token), auth_token); } /** * Delete a coupon from a basket + * * @return Resource * @throws IOException */ public Resource deleteBasketCoupon() throws IOException { URL url = new URL(PublicURLS.Basket.deleteBasketCoupon().set("companyId", this.id).expand()); - return new Resource(HttpService.api_DELETE(url), auth_token); + return new Resource(PlainHttpService.api_DELETE(url), auth_token); } public Booking bookingCreate_Admin(BookingCreateParams bCParams) throws IOException { String urlStr = AdminURLS.Bookings.bookingCreate().set("companyId", this.id).expand(); - URL url = new URL (urlStr); - - return new Booking(HttpService.api_POST(url, bCParams.getParams(), auth_token), auth_token); - } + URL url = new URL(urlStr); - /** - * getBookingList - * @return BBCollection - * @throws IOException - */ - public BBCollection bookingList_Admin(BookingListParams bLParams) throws IOException { - URL url; - if(getLink("bookings") != null) - url = new URL(Utils.inflateLink(getLink("bookings"), bLParams.getParams())); - else { - UriTemplate template = AdminURLS.Bookings.bookingList().set("companyId", this.id); - url = new URL(Utils.inflateLink(template, bLParams.getParams())); - } - BBCollection bookings = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "bookings", Booking.class); - return bookings; + return new Booking(PlainHttpService.api_POST(url, bCParams.getParams(), auth_token), auth_token); } - /** * getBookingRead_Admin + * * @param bookingId * @return Booking * @throws IOException */ public Booking bookingRead_Admin(String bookingId) throws IOException { - URL url = new URL (AdminURLS.Bookings.bookingRead().set("companyId", this.id).set("bookingId", bookingId).expand()); - BBCollection bookings = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "booking", Booking.class); + URL url = new URL(AdminURLS.Bookings.bookingRead().set("companyId", this.id).set("bookingId", bookingId).expand()); + BBCollection bookings = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "booking", Booking.class); return bookings.getObjectAtIndex(0); } - - /** * Get all the coupons for a Company. + * * @return BBCollection * @throws IOException */ public BBCollection couponsList_Admin() throws IOException { - URL url = new URL (AdminURLS.Coupons.couponList().set("companyId", this.id).expand()); - BBCollection coupons = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "coupons", Coupons.class); + URL url = new URL(AdminURLS.Coupons.couponList().set("companyId", this.id).expand()); + BBCollection coupons = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "coupons", Coupons.class); return coupons; } - /** - * List of Clients for a Company. - * @param clParams - * @return BBCollection - * @throws IOException - */ - public BBCollection clientList_Admin(ClientListParams clParams) throws IOException { - String urlStr = AdminURLS.Client.clientList().set("companyId", this.id).expand(); - URL url = new URL(Utils.inflateLink(urlStr, clParams.getParams())); - BBCollection clients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); - return clients; - } - - - /** - * Load a Specific Client Details. - * @param clientId - * @return Client - * @throws IOException - */ - public Client clientRead_Admin(String clientId) throws IOException { - URL url = new URL (AdminURLS.Client.clientRead().set("companyId", this.id).set("clientId", clientId).expand()); - BBCollection clients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); - return clients.getObjectAtIndex(0); - } - - /** - * Create a Client for a company - * @param cCParams - * @return Client - * @throws IOException - */ - public Client clientCreate_Admin(ClientCreateParams cCParams) throws IOException { - String urlStr = AdminURLS.Client.clientCreate().set("companyId", this.id).expand(); - URL url = new URL (urlStr); - - return new Client(HttpService.api_POST(url, cCParams.getParams(), auth_token), auth_token); - } - - /** * Read details about a logged in user, including details about which companies they have access to. + * * @param userId * @return User * @throws IOException */ public User userRead_Admin(String userId) throws IOException { - URL url = new URL (AdminURLS.User.userRead().set("companyId", this.id).set("userId", userId).expand()); - BBCollection users = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "user", User.class); + URL url = new URL(AdminURLS.User.userRead().set("companyId", this.id).set("userId", userId).expand()); + BBCollection users = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "user", User.class); return users.getObjectAtIndex(0); } - /** - * Get a Specific Client Details using a Reference ID - * @param crrParams - * @param referenceId - * @return Client - * @throws IOException - */ - public Client clientReadByRef_Admin(ClientReadRefParams crrParams, String referenceId) throws IOException { - String urlStr = AdminURLS.Client.clientReadUsingRefId().set("companyId", this.id).set("referenceId", referenceId).expand(); - URL url = new URL(Utils.inflateLink(urlStr, crrParams.getParams())); - BBCollection clients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); - return clients.getObjectAtIndex(0); - } - - - /** - * Get a Specific Client Details from their email - * @param creParams - * @param email - * @return Client - * @throws IOException - */ - public Client clientReadByEmail_Admin(ClientReadEmailParams creParams, String email) throws IOException { - String urlStr = AdminURLS.Client.clientReadUsingEmail().set("companyId", this.id).set("email", email).expand(); - URL url = new URL(Utils.inflateLink(urlStr, creParams.getParams())); - BBCollection clients = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "clients", Client.class); - return clients.getObjectAtIndex(0); - } - - /** * Get a list of Purchases. + * * @param plParams * @return BBCollection * @throws IOException @@ -1223,25 +1213,27 @@ public Client clientReadByEmail_Admin(ClientReadEmailParams creParams, String em public BBCollection purchaseList_Admin(PurchaseListParams plParams) throws IOException { String urlStr = AdminURLS.Purchase.purchaseList().set("companyId", this.id).expand(); URL url = new URL(Utils.inflateLink(urlStr, plParams.getParams())); - BBCollection purchases = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "purchases", Purchase.class); + BBCollection purchases = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "purchases", Purchase.class); return purchases; } /** * Get a Specific Purchase + * * @param purchaseId * @return Purchase * @throws IOException */ public Purchase purchaseRead_Admin(String purchaseId) throws IOException { - URL url = new URL (AdminURLS.Purchase.purchaseRead().set("companyId", this.id).set("purchaseId", purchaseId).expand()); - BBCollection purchases = new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "purchase", Purchase.class); + URL url = new URL(AdminURLS.Purchase.purchaseRead().set("companyId", this.id).set("purchaseId", purchaseId).expand()); + BBCollection purchases = new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "purchase", Purchase.class); return purchases.getObjectAtIndex(0); } /** * Get the Client Schema + * * @return BBRoot * @throws IOException */ @@ -1275,6 +1267,7 @@ public BBRoot getClientSchema() throws IOException { /** * Create a new Client + * * @param data * @return BBRoot * @throws HttpException @@ -1282,12 +1275,13 @@ public BBRoot getClientSchema() throws IOException { */ public BBRoot createClient(Map data) throws HttpException, MalformedURLException { String link = response.getRep().getLinkByRel("client").getHref(); - URL url = new URL (link); - return new BBRoot(HttpService.api_POST(url, data, auth_token), auth_token); + URL url = new URL(link); + return new BBRoot(PlainHttpService.api_POST(url, data, auth_token), auth_token); } /** * Create a new Person + * * @param data * @return BBRoot * @throws HttpException @@ -1295,34 +1289,36 @@ public BBRoot createClient(Map data) throws HttpException, Malfo */ public BBRoot createPerson(Map data) throws HttpException, MalformedURLException { String uri = AdminURLS.Person.personCreate().set("companyId", get("id")).expand(); - URL url = new URL (uri); - return new BBRoot(HttpService.api_POST(url, data, auth_token), auth_token); + URL url = new URL(uri); + return new BBRoot(PlainHttpService.api_POST(url, data, auth_token), auth_token); } /** * Update a person + * * @param person * @param data * @return BBRoot * @throws HttpException * @throws MalformedURLException */ - public BBRoot updatePerson(People person, Map data) throws HttpException, MalformedURLException { + public BBRoot updatePerson(Person person, Map data) throws HttpException, MalformedURLException { String uri = AdminURLS.Person.personUpdate().set("companyId", get("id")).set("personId", person.get("id")).expand(); - URL url = new URL (uri); - return new BBRoot(HttpService.api_PUT(url, HttpService.jsonContentType, data, auth_token), auth_token); + URL url = new URL(uri); + return new BBRoot(PlainHttpService.api_PUT(url, PlainHttpService.jsonContentType, data, auth_token), auth_token); } /** * Get the administrators + * * @return Administrator * @throws IOException */ public Administrator getAdministrators() throws IOException { - if(administratorList == null) { + if (administratorList == null) { String link = response.getRep().getLinkByRel("administrators").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - HttpServiceResponse response = HttpService.api_GET(url, auth_token); + HttpServiceResponse response = PlainHttpService.api_GET(url, auth_token); administratorList = new Administrator(response, auth_token); } return administratorList; @@ -1330,14 +1326,15 @@ public Administrator getAdministrators() throws IOException { /** * Get the administrator schema + * * @return BBRoot * @throws IOException */ public BBRoot getAdministratorSchema() throws IOException { - if(administratorSchema == null) { + if (administratorSchema == null) { String link = response.getRep().getLinkByRel("new_administrator").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - HttpServiceResponse response = HttpService.api_GET(url, auth_token); + HttpServiceResponse response = PlainHttpService.api_GET(url, auth_token); administratorSchema = new BBRoot(response, auth_token); } return administratorSchema; @@ -1345,6 +1342,7 @@ public BBRoot getAdministratorSchema() throws IOException { /** * Create a new administrator + * * @param data * @return Administrator * @throws HttpException @@ -1352,12 +1350,13 @@ public BBRoot getAdministratorSchema() throws IOException { */ public Administrator createAdministrator(Map data) throws HttpException, MalformedURLException { String uri = AdminURLS.Administrator.administratorCreate().set("companyId", get("id")).expand(); - URL url = new URL (uri); - return new Administrator(HttpService.api_POST(url, data, auth_token), auth_token); + URL url = new URL(uri); + return new Administrator(PlainHttpService.api_POST(url, data, auth_token), auth_token); } /** * Update a person + * * @param data * @return BBRoot * @throws HttpException @@ -1365,8 +1364,8 @@ public Administrator createAdministrator(Map data) throws HttpEx */ public BBRoot updatePerson(Map data) throws HttpException, MalformedURLException { String uri = AdminURLS.Person.personCreate().set("companyId", get("id")).expand(); - URL url = new URL (uri); - return new BBRoot(HttpService.api_POST(url, data, auth_token), auth_token); + URL url = new URL(uri); + return new BBRoot(PlainHttpService.api_POST(url, data, auth_token), auth_token); } /** @@ -1779,7 +1778,7 @@ public String getNewResourceLink() { * * @return The schedules link associated with the current Company object */ - public String getSchedules() { + public String getSchedulesLink() { return getLink("schedules"); } @@ -1891,4 +1890,44 @@ public String getExternalBookings() { return getLink("external_bookings"); } + /** + * Check if company has resources configured + * + * @return true if the company has resources configured + */ + public boolean hasResources() { + //TODO: Use settings when BB updates the api + return getResourcesLink() != null; + } + + /** + * Check if company has events configured + * + * @return true if the company has events configured + */ + public boolean hasEvents() { + //TODO: Use settings when BB updates the api + return getEventsLink() != null; + } + + /** + * Check if company has services configured + * + * @return true if the company has services configured + */ + public boolean hasServices() { + //TODO: Use settings when BB updates the api + return getServicesLink() != null; + } + + /** + * Check if company has people configured + * + * @return true if the company has people configured + */ + public boolean hasPeople() { + //TODO: Use settings when BB updates the api + return getPeopleLink() != null; + } + } diff --git a/src/main/bookingbugAPI/models/CompanyConfig.java b/src/main/bookingbugAPI2/models/CompanyConfig.java similarity index 83% rename from src/main/bookingbugAPI/models/CompanyConfig.java rename to src/main/bookingbugAPI2/models/CompanyConfig.java index bb37c33..a9fdd8c 100644 --- a/src/main/bookingbugAPI/models/CompanyConfig.java +++ b/src/main/bookingbugAPI2/models/CompanyConfig.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class CompanyConfig extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/CompanySettings.java b/src/main/bookingbugAPI2/models/CompanySettings.java similarity index 95% rename from src/main/bookingbugAPI/models/CompanySettings.java rename to src/main/bookingbugAPI2/models/CompanySettings.java index 2a4a0b2..567b777 100644 --- a/src/main/bookingbugAPI/models/CompanySettings.java +++ b/src/main/bookingbugAPI2/models/CompanySettings.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; /** * Created by sebi on 31.03.2016. @@ -119,8 +119,8 @@ public boolean hasWallets() { * * @return the payment tax associated with the current company settings. */ - public int getPaymentTax() { - return getInteger("payment_tax", 0); + public double getPaymentTax() { + return getDouble("payment_tax", 0.0); } /** diff --git a/src/main/bookingbugAPI/models/Coupon.java b/src/main/bookingbugAPI2/models/Coupon.java similarity index 98% rename from src/main/bookingbugAPI/models/Coupon.java rename to src/main/bookingbugAPI2/models/Coupon.java index c2ddcb5..36fd8bc 100644 --- a/src/main/bookingbugAPI/models/Coupon.java +++ b/src/main/bookingbugAPI2/models/Coupon.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; diff --git a/src/main/bookingbugAPI/models/Coupons.java b/src/main/bookingbugAPI2/models/Coupons.java similarity index 82% rename from src/main/bookingbugAPI/models/Coupons.java rename to src/main/bookingbugAPI2/models/Coupons.java index 210a3ef..9452ea8 100644 --- a/src/main/bookingbugAPI/models/Coupons.java +++ b/src/main/bookingbugAPI2/models/Coupons.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Coupons extends BBRoot { diff --git a/src/main/bookingbugAPI/models/Currency.java b/src/main/bookingbugAPI2/models/Currency.java similarity index 95% rename from src/main/bookingbugAPI/models/Currency.java rename to src/main/bookingbugAPI2/models/Currency.java index 1cf3c6b..631b1b3 100644 --- a/src/main/bookingbugAPI/models/Currency.java +++ b/src/main/bookingbugAPI2/models/Currency.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; /** * Created by sebi on 31.03.2016. diff --git a/src/main/bookingbugAPI/models/Deal.java b/src/main/bookingbugAPI2/models/Deal.java similarity index 97% rename from src/main/bookingbugAPI/models/Deal.java rename to src/main/bookingbugAPI2/models/Deal.java index 481c751..9351961 100644 --- a/src/main/bookingbugAPI/models/Deal.java +++ b/src/main/bookingbugAPI2/models/Deal.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; diff --git a/src/main/bookingbugAPI/models/DealCodes.java b/src/main/bookingbugAPI2/models/DealCodes.java similarity index 82% rename from src/main/bookingbugAPI/models/DealCodes.java rename to src/main/bookingbugAPI2/models/DealCodes.java index d65aee1..34252b7 100644 --- a/src/main/bookingbugAPI/models/DealCodes.java +++ b/src/main/bookingbugAPI2/models/DealCodes.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class DealCodes extends BBRoot { diff --git a/src/main/bookingbugAPI/models/Event.java b/src/main/bookingbugAPI2/models/Event.java similarity index 92% rename from src/main/bookingbugAPI/models/Event.java rename to src/main/bookingbugAPI2/models/Event.java index 58b0f7c..f50c2a8 100644 --- a/src/main/bookingbugAPI/models/Event.java +++ b/src/main/bookingbugAPI2/models/Event.java @@ -1,14 +1,12 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.joda.time.DateTime; import java.io.IOException; import java.net.URL; -import java.util.Date; public class Event extends BBRoot { @@ -30,7 +28,7 @@ public SchemaForm getNewBookingSchema() throws IOException { if (getLink("new_booking") != null) { String link = getLink("new_booking"); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new SchemaForm(HttpService.api_GET(url, this.auth_token)); + return new SchemaForm(PlainHttpService.api_GET(url, this.auth_token)); } // Throw exception: link is missing throw new IOException("new_booking link missing"); @@ -197,4 +195,13 @@ public String getEventChainsLink() { public String getBookLink() { return getLink("book"); } + + /** + * Returns the new booking link + * + * @return the link to create a new booking + */ + public String getNewBookingLink() { + return getLink("new_booking"); + } } diff --git a/src/main/bookingbugAPI/models/EventChain.java b/src/main/bookingbugAPI2/models/EventChain.java similarity index 91% rename from src/main/bookingbugAPI/models/EventChain.java rename to src/main/bookingbugAPI2/models/EventChain.java index a5164fa..b81c700 100644 --- a/src/main/bookingbugAPI/models/EventChain.java +++ b/src/main/bookingbugAPI2/models/EventChain.java @@ -1,11 +1,11 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.PublicURLS; -import bookingbugAPI.models.params.EventListParams; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.api.PublicURLS; +import bookingbugAPI2.models.params.EventListParams; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import rx.Observable; @@ -31,7 +31,7 @@ public EventChain() { public SchemaForm getNewBookingSchema() throws IOException { URL url = new URL(UriTemplate.fromTemplate(this.getRep().getLinkByRel("new_booking").getHref()).expand()); - return new SchemaForm(HttpService.api_GET(url, this.auth_token)); + return new SchemaForm(PlainHttpService.api_GET(url, this.auth_token)); } /** @@ -53,7 +53,7 @@ public BBCollection eventList(EventListParams params) throws IOException } URL url = new URL(template.expand(params.getParamsMapObj())); - return new BBCollection(HttpService.api_GET(url, auth_token), auth_token, "events", Event.class); + return new BBCollection(PlainHttpService.api_GET(url, auth_token), auth_token, "events", Event.class); } public Observable> eventListObs(final EventListParams params) { @@ -236,6 +236,15 @@ public String getQuestionsLink() { return getLink("questions"); } + /** + * Returns the events link + * + * @return The events link associated with current EventChain object + */ + public String getEventsLink() { + return getLink("events"); + } + /** * Returns the child event chains. * diff --git a/src/main/bookingbugAPI/models/EventGroup.java b/src/main/bookingbugAPI2/models/EventGroup.java similarity index 94% rename from src/main/bookingbugAPI/models/EventGroup.java rename to src/main/bookingbugAPI2/models/EventGroup.java index 4e49870..e3c8f70 100644 --- a/src/main/bookingbugAPI/models/EventGroup.java +++ b/src/main/bookingbugAPI2/models/EventGroup.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class EventGroup extends BBRoot { diff --git a/src/main/bookingbugAPI/models/HttpException.java b/src/main/bookingbugAPI2/models/HttpException.java similarity index 91% rename from src/main/bookingbugAPI/models/HttpException.java rename to src/main/bookingbugAPI2/models/HttpException.java index 72d9694..dc97956 100644 --- a/src/main/bookingbugAPI/models/HttpException.java +++ b/src/main/bookingbugAPI2/models/HttpException.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import java.io.IOException; @@ -51,7 +51,7 @@ public String getRawResponse() { @Override public String toString(){ - return errorMessage; + return "Message: " + errorMessage + "\nBody: " + rawResponse; } } diff --git a/src/main/bookingbugAPI/models/Login.java b/src/main/bookingbugAPI2/models/Login.java similarity index 77% rename from src/main/bookingbugAPI/models/Login.java rename to src/main/bookingbugAPI2/models/Login.java index eb40453..ee052c1 100644 --- a/src/main/bookingbugAPI/models/Login.java +++ b/src/main/bookingbugAPI2/models/Login.java @@ -1,16 +1,15 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.AdminURLS; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.api.AdminURLS; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; import com.theoryinpractise.halbuilder.api.ContentRepresentation; import com.theoryinpractise.halbuilder.api.Link; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; -import java.util.HashMap; import java.util.List; import java.util.Map; @@ -40,15 +39,12 @@ public Login login(Map params) throws IOException { } /** - * Returns the admin credentials. - * - * @return the credentials associated with the current Login object. + * Returns true if Login is associated to multiple companies + * When authenticating users must call this method and if true, authenticate with administrator instead + * @return */ - public Map getCredentials() { - Map credentials = new HashMap<>(); - credentials.put("email", email); - credentials.put("password", password); - return credentials; + public boolean isMultiLogin() { + return getAuthToken() == null; } /** @@ -128,29 +124,19 @@ public Administrator getAdministrator() throws IOException { if (admin_reps.size() == 0 || administrator == null) { String link = getRep().getLinkByRel("administrator").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - administrator = new Administrator(HttpService.api_GET(url, auth_token), auth_token); + administrator = new Administrator(PlainHttpService.api_GET(url, auth_token), auth_token); } } return administrator; } - /** - *Returns the administrator from inserted link. - * @param link - * @return the administrator associated with the current login object. - * @throws IOException - */ - public Administrator getAdministrator(Link link) throws IOException { - URL url = new URL(UriTemplate.fromTemplate(link.getHref()).expand()); - return new Administrator(HttpService.api_GET(url, auth_token), auth_token); - } /**Returns the list of administrators * * @return */ public BBCollection getAdministrators() { - return new BBCollection(new HttpServiceResponse(getResource("administrators")), auth_token, Administrator.class); + return new BBCollection<>(new HttpServiceResponse(getRep()), auth_token, "administrators", Administrator.class); } /** @@ -163,7 +149,7 @@ public BBCollection getAdministrators() { public Administrator createAdministrator(Map data) throws HttpException, MalformedURLException { String uri = AdminURLS.Administrator.administratorCreate().set("companyId", get("company_id")).expand(); URL url = new URL(uri); - return new Administrator(HttpService.api_POST(url, data, auth_token), auth_token); + return new Administrator(PlainHttpService.api_POST(url, data, auth_token), auth_token); } /** @@ -176,7 +162,7 @@ public Administrator createAdministrator(Map data) throws HttpEx */ public Administrator updateAdministrator(Link link, Map data) throws HttpException, MalformedURLException { URL url = new URL(UriTemplate.fromTemplate(link.getHref()).expand()); - return new Administrator(HttpService.api_PUT(url, HttpService.jsonContentType, data, auth_token), auth_token); + return new Administrator(PlainHttpService.api_PUT(url, PlainHttpService.jsonContentType, data, auth_token), auth_token); } /** @@ -187,6 +173,6 @@ public Administrator updateAdministrator(Link link, Map data) th */ public Member getMember(Link link) throws IOException { URL url = new URL(UriTemplate.fromTemplate(link.getHref()).expand()); - return new Member(HttpService.api_GET(url, auth_token), auth_token); + return new Member(PlainHttpService.api_GET(url, auth_token), auth_token); } } diff --git a/src/main/bookingbugAPI/models/Member.java b/src/main/bookingbugAPI2/models/Member.java similarity index 97% rename from src/main/bookingbugAPI/models/Member.java rename to src/main/bookingbugAPI2/models/Member.java index 79a91f7..d3c2be5 100644 --- a/src/main/bookingbugAPI/models/Member.java +++ b/src/main/bookingbugAPI2/models/Member.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.io.IOException; import java.net.URL; @@ -17,7 +17,7 @@ public Member(HttpServiceResponse httpServiceResponse, String auth_token) { public BBRoot getSchema() throws IOException{ String link = getRep().getLinkByRel("edit_member").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - HttpServiceResponse schema_rep = HttpService.api_GET(url, auth_token); + HttpServiceResponse schema_rep = PlainHttpService.api_GET(url, auth_token); return new BBRoot(schema_rep); } diff --git a/src/main/bookingbugAPI/models/MultiStatus.java b/src/main/bookingbugAPI2/models/MultiStatus.java similarity index 88% rename from src/main/bookingbugAPI/models/MultiStatus.java rename to src/main/bookingbugAPI2/models/MultiStatus.java index 1ae2cf2..7bc2c6f 100644 --- a/src/main/bookingbugAPI/models/MultiStatus.java +++ b/src/main/bookingbugAPI2/models/MultiStatus.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.annotation.JsonProperty; /** diff --git a/src/main/bookingbugAPI/models/Note.java b/src/main/bookingbugAPI2/models/Note.java similarity index 88% rename from src/main/bookingbugAPI/models/Note.java rename to src/main/bookingbugAPI2/models/Note.java index f1f9661..4d3dbd5 100644 --- a/src/main/bookingbugAPI/models/Note.java +++ b/src/main/bookingbugAPI2/models/Note.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Note extends BBRoot { diff --git a/src/main/bookingbugAPI/models/Notes.java b/src/main/bookingbugAPI2/models/Notes.java similarity index 95% rename from src/main/bookingbugAPI/models/Notes.java rename to src/main/bookingbugAPI2/models/Notes.java index 06c087d..76428a5 100644 --- a/src/main/bookingbugAPI/models/Notes.java +++ b/src/main/bookingbugAPI2/models/Notes.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/src/main/bookingbugAPI/models/Option.java b/src/main/bookingbugAPI2/models/Option.java similarity index 96% rename from src/main/bookingbugAPI/models/Option.java rename to src/main/bookingbugAPI2/models/Option.java index 25f192e..88b73e6 100644 --- a/src/main/bookingbugAPI/models/Option.java +++ b/src/main/bookingbugAPI2/models/Option.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; diff --git a/src/main/bookingbugAPI/models/People.java b/src/main/bookingbugAPI2/models/Person.java similarity index 90% rename from src/main/bookingbugAPI/models/People.java rename to src/main/bookingbugAPI2/models/Person.java index 93d2d92..aeec592 100644 --- a/src/main/bookingbugAPI/models/People.java +++ b/src/main/bookingbugAPI2/models/Person.java @@ -1,32 +1,32 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.damnhandy.uri.template.UriTemplate; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.theoryinpractise.halbuilder.api.Link; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import java.io.IOException; import java.net.URL; import java.util.List; -public class People extends BBRoot{ +public class Person extends BBRoot{ private BBRoot schema; - public People(HttpServiceResponse httpServiceResponse){ + public Person(HttpServiceResponse httpServiceResponse){ super(httpServiceResponse); } - public People(HttpServiceResponse httpServiceResponse, String auth_token){ + public Person(HttpServiceResponse httpServiceResponse, String auth_token){ super(httpServiceResponse); this.auth_token = auth_token; } - public People() { + public Person() { super(); } @@ -216,15 +216,15 @@ public BBRoot getSchema() throws IOException{ if(schema == null){ String link = getRep().getLinkByRel("new").getHref(); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - schema = new BBRoot(HttpService.api_GET(url, auth_token)); + schema = new BBRoot(PlainHttpService.api_GET(url, auth_token)); } return schema; } - public People getPerson(Link link) throws IOException{ + public Person getPerson(Link link) throws IOException{ String absUrl = Utils.absoluteURL(link.getHref()); URL url = new URL(UriTemplate.fromTemplate(absUrl).expand()); - return new People(HttpService.api_GET(url, auth_token), auth_token); + return new Person(PlainHttpService.api_GET(url, auth_token), auth_token); } } diff --git a/src/main/bookingbugAPI/models/Product.java b/src/main/bookingbugAPI2/models/Product.java similarity index 82% rename from src/main/bookingbugAPI/models/Product.java rename to src/main/bookingbugAPI2/models/Product.java index 9afc7e9..5001410 100644 --- a/src/main/bookingbugAPI/models/Product.java +++ b/src/main/bookingbugAPI2/models/Product.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Product extends BBRoot { diff --git a/src/main/bookingbugAPI/models/PublicRoot.java b/src/main/bookingbugAPI2/models/PublicRoot.java similarity index 69% rename from src/main/bookingbugAPI/models/PublicRoot.java rename to src/main/bookingbugAPI2/models/PublicRoot.java index 32eb8fe..84b53dc 100644 --- a/src/main/bookingbugAPI/models/PublicRoot.java +++ b/src/main/bookingbugAPI2/models/PublicRoot.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class PublicRoot extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/Purchase.java b/src/main/bookingbugAPI2/models/Purchase.java similarity index 81% rename from src/main/bookingbugAPI/models/Purchase.java rename to src/main/bookingbugAPI2/models/Purchase.java index 1aaa17b..68d8774 100644 --- a/src/main/bookingbugAPI/models/Purchase.java +++ b/src/main/bookingbugAPI2/models/Purchase.java @@ -1,9 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.api.PublicURLS; -import bookingbugAPI.services.HttpService; -import com.theoryinpractise.halbuilder.api.ContentRepresentation; -import helpers.HttpServiceResponse; +import bookingbugAPI2.api.PublicURLS; +import bookingbugAPI2.services.http.PlainHttpService; +import helpers2.HttpServiceResponse; import java.io.IOException; import java.net.URL; @@ -36,7 +35,7 @@ public Purchase() {} */ public Resource purchaseReadTotal(String companyId, String purchaseTotalId) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseReadTotal().set("companyId", companyId).set("purchaseTotalId", purchaseTotalId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -49,7 +48,7 @@ public Resource purchaseReadTotal(String companyId, String purchaseTotalId) thro */ public Resource purchaseReadItem(String companyId, String purchaseTotalId) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseReadItem().set("companyId", companyId).set("purchaseTotalId", purchaseTotalId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -61,7 +60,7 @@ public Resource purchaseReadItem(String companyId, String purchaseTotalId) throw */ public Resource purchaseRead(String purchaseId) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseRead().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -73,7 +72,7 @@ public Resource purchaseRead(String purchaseId) throws IOException { */ public Resource purchaseFindByBookingRef(String bookingRefId) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseFindByBookingRef().set("bookingRefId", bookingRefId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -85,7 +84,7 @@ public Resource purchaseFindByBookingRef(String bookingRefId) throws IOException */ public Resource purchaseUpdate(String purchaseId, Map params) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseUpdate().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_PUT(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_PUT(url, params, auth_token), auth_token); } @@ -98,7 +97,7 @@ public Resource purchaseUpdate(String purchaseId, Map params) thr */ public Resource bookWaitlistItem(String purchaseId) throws IOException { URL url = new URL(PublicURLS.Purchase.bookWaitlistItem().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -110,7 +109,7 @@ public Resource bookWaitlistItem(String purchaseId) throws IOException { */ public Resource deleteBookingsForPurchase(String purchaseId) throws IOException { URL url = new URL(PublicURLS.Purchase.deleteBookingsForPurchase().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_DELETE(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_DELETE(url, auth_token), auth_token); } @@ -123,7 +122,7 @@ public Resource deleteBookingsForPurchase(String purchaseId) throws IOException */ public Resource bookingRead(String purchaseId, String bookingId) throws IOException { URL url = new URL(PublicURLS.Purchase.bookingRead().set("purchaseId", purchaseId).set("bookingId", bookingId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -136,7 +135,7 @@ public Resource bookingRead(String purchaseId, String bookingId) throws IOExcept */ public Resource bookingUpdate(String purchaseId, String bookingId, Map params) throws IOException { URL url = new URL(PublicURLS.Purchase.bookingUpdate().set("purchaseId", purchaseId).set("bookingId", bookingId).expand()); - return new Resource(HttpService.api_PUT(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_PUT(url, params, auth_token), auth_token); } @@ -149,7 +148,7 @@ public Resource bookingUpdate(String purchaseId, String bookingId, Map params) throws IOException { URL url = new URL(PublicURLS.Purchase.bookingAttachementAdd().set("purchaseId", purchaseId).set("bookingId", bookingId).expand()); - return new Resource(HttpService.api_POST(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_POST(url, params, auth_token), auth_token); } @@ -175,7 +174,7 @@ public Resource bookingAttachementAdd(String purchaseId, String bookingId, Map params) throws IOException { URL url = new URL(PublicURLS.Purchase.bookingAttachementAddOrUpdate().set("purchaseId", purchaseId).set("bookingId", bookingId).expand()); - return new Resource(HttpService.api_PUT(url, params, auth_token), auth_token); + return new Resource(PlainHttpService.api_PUT(url, params, auth_token), auth_token); } @@ -187,7 +186,7 @@ public Resource bookingAttachementAddOrUpdate(String purchaseId, String bookingI */ public Resource bookingAttachementList(String purchaseId) throws IOException { URL url = new URL(PublicURLS.Purchase.bookingAttachementList().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } @@ -199,7 +198,7 @@ public Resource bookingAttachementList(String purchaseId) throws IOException { */ public Resource purchaseDealsList(String purchaseId) throws IOException { URL url = new URL(PublicURLS.Purchase.purchaseDealsList().set("purchaseId", purchaseId).expand()); - return new Resource(HttpService.api_GET(url, auth_token), auth_token); + return new Resource(PlainHttpService.api_GET(url, auth_token), auth_token); } } diff --git a/src/main/bookingbugAPI/models/Question.java b/src/main/bookingbugAPI2/models/Question.java similarity index 96% rename from src/main/bookingbugAPI/models/Question.java rename to src/main/bookingbugAPI2/models/Question.java index a801e78..c7833e1 100644 --- a/src/main/bookingbugAPI/models/Question.java +++ b/src/main/bookingbugAPI2/models/Question.java @@ -1,7 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import com.fasterxml.jackson.annotation.JsonProperty; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import java.util.List; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/Resource.java b/src/main/bookingbugAPI2/models/Resource.java similarity index 91% rename from src/main/bookingbugAPI/models/Resource.java rename to src/main/bookingbugAPI2/models/Resource.java index 793618c..377a3bd 100644 --- a/src/main/bookingbugAPI/models/Resource.java +++ b/src/main/bookingbugAPI2/models/Resource.java @@ -1,7 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import com.j256.ormlite.stmt.query.In; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Resource extends BBRoot { @@ -91,6 +90,14 @@ public Integer getOrder() { return getInteger("order", INTEGER_DEFAULT_VALUE); } + /** + * Returns the edit link + * @return the link to edit this service + */ + public String getEditLink() { + return getLink("edit"); + } + /** * Returns the items link. * diff --git a/src/main/bookingbugAPI2/models/Schedule.java b/src/main/bookingbugAPI2/models/Schedule.java new file mode 100644 index 0000000..3f47fbc --- /dev/null +++ b/src/main/bookingbugAPI2/models/Schedule.java @@ -0,0 +1,26 @@ +package bookingbugAPI2.models; + +import helpers2.HttpServiceResponse; + + +public class Schedule extends BBRoot { + public Schedule(HttpServiceResponse httpServiceResponse) { + super(httpServiceResponse); + } + + public Schedule(HttpServiceResponse httpServiceResponse, String auth_token) { + super(httpServiceResponse, auth_token); + } + + public String getName() { + return get("name"); + } + + public String getDesc() { + return get("desc"); + } + + public Integer getStyle() { + return getInteger("style", INTEGER_DEFAULT_VALUE); + } +} diff --git a/src/main/bookingbugAPI/models/SchemaForm.java b/src/main/bookingbugAPI2/models/SchemaForm.java similarity index 94% rename from src/main/bookingbugAPI/models/SchemaForm.java rename to src/main/bookingbugAPI2/models/SchemaForm.java index 3c98cd7..de8a388 100644 --- a/src/main/bookingbugAPI/models/SchemaForm.java +++ b/src/main/bookingbugAPI2/models/SchemaForm.java @@ -1,11 +1,9 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.JsonNodeFactory; -import helpers.HttpServiceResponse; - -import java.util.Map; +import helpers2.HttpServiceResponse; /** * Created by sebi on 11.04.2016. diff --git a/src/main/bookingbugAPI/models/Service.java b/src/main/bookingbugAPI2/models/Service.java similarity index 86% rename from src/main/bookingbugAPI/models/Service.java rename to src/main/bookingbugAPI2/models/Service.java index 091ece9..bf9efa9 100644 --- a/src/main/bookingbugAPI/models/Service.java +++ b/src/main/bookingbugAPI2/models/Service.java @@ -1,13 +1,15 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.damnhandy.uri.template.UriTemplate; import com.theoryinpractise.halbuilder.api.Link; -import helpers.HttpServiceResponse; -import helpers.Utils; +import com.theoryinpractise.halbuilder.api.RepresentationException; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import java.io.IOException; import java.net.URL; +import java.util.LinkedList; import java.util.List; @@ -26,18 +28,11 @@ public Service(HttpServiceResponse httpServiceResponse, String auth_token) { public Service() { } - public String get_editServiceLik() { - return getLink("edit"); - } - public String get_newBookingLik() { - return getLink("new_booking"); - } - public SchemaForm getNewBookingSchema() throws IOException { if(getLink("new_booking") != null) { String link = getLink("new_booking"); URL url = new URL(UriTemplate.fromTemplate(link).expand()); - return new SchemaForm(HttpService.api_GET(url, this.auth_token)); + return new SchemaForm(PlainHttpService.api_GET(url, this.auth_token)); } // Throw exception: link is missing throw new IOException("new_booking link missing"); @@ -46,7 +41,7 @@ public SchemaForm getNewBookingSchema() throws IOException { public Service getService(Link link) throws IOException { String absUrl = Utils.absoluteURL(link.getHref()); URL url = new URL(UriTemplate.fromTemplate(absUrl).expand()); - Service service = new Service(HttpService.api_GET(url, auth_token), auth_token); + Service service = new Service(PlainHttpService.api_GET(url, auth_token), auth_token); return service; } @@ -69,12 +64,18 @@ public String getName(){ } /** - * Returns the service durations. + * Returns the service durations. If there is no durations key return a list containing 1 * * @return the service durations associated with the current Service object. */ public List getDurations(){ - return getObjects("durations", Integer.class); + try { + return getObjects("durations", Integer.class); + } catch (RepresentationException e) { + List res = new LinkedList<>(); + res.add(1); + return res; + } } /** @@ -83,7 +84,11 @@ public List getDurations(){ * @return the service prices associated with the current Service object. */ public List getPrices(){ - return getIntegerArray("prices"); + try { + return getIntegerArray("prices"); + } catch (RepresentationException e) { + return new LinkedList<>(); + } } /** @@ -230,6 +235,22 @@ public Boolean getChildLevelService(){ return getBoolean("child_level_service", BOOLEAN_DEFAULT_VALUE); } + /** + * Returns the edit link + * @return the link to edit this service + */ + public String getEditLink() { + return getLink("edit"); + } + + /** + * Returns the new booking link + * @return the link to create a new booking + */ + public String getNewBookingLink() { + return getLink("new_booking"); + } + /** * Returns the items link. * diff --git a/src/main/bookingbugAPI/models/Session.java b/src/main/bookingbugAPI2/models/Session.java similarity index 82% rename from src/main/bookingbugAPI/models/Session.java rename to src/main/bookingbugAPI2/models/Session.java index c7cb447..d115e7f 100644 --- a/src/main/bookingbugAPI/models/Session.java +++ b/src/main/bookingbugAPI2/models/Session.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Session extends BBRoot { diff --git a/src/main/bookingbugAPI/models/Slot.java b/src/main/bookingbugAPI2/models/Slot.java similarity index 81% rename from src/main/bookingbugAPI/models/Slot.java rename to src/main/bookingbugAPI2/models/Slot.java index 849653d..5206ea9 100644 --- a/src/main/bookingbugAPI/models/Slot.java +++ b/src/main/bookingbugAPI2/models/Slot.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class Slot extends BBRoot { diff --git a/src/main/bookingbugAPI/models/SurveyQuestion.java b/src/main/bookingbugAPI2/models/SurveyQuestion.java similarity index 83% rename from src/main/bookingbugAPI/models/SurveyQuestion.java rename to src/main/bookingbugAPI2/models/SurveyQuestion.java index 495263c..79056b6 100644 --- a/src/main/bookingbugAPI/models/SurveyQuestion.java +++ b/src/main/bookingbugAPI2/models/SurveyQuestion.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class SurveyQuestion extends BBRoot { diff --git a/src/main/bookingbugAPI/models/User.java b/src/main/bookingbugAPI2/models/User.java similarity index 81% rename from src/main/bookingbugAPI/models/User.java rename to src/main/bookingbugAPI2/models/User.java index 7df1d7e..e9ee1ae 100644 --- a/src/main/bookingbugAPI/models/User.java +++ b/src/main/bookingbugAPI2/models/User.java @@ -1,6 +1,6 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; public class User extends BBRoot{ diff --git a/src/main/bookingbugAPI/models/params/AddressListParams.java b/src/main/bookingbugAPI2/models/params/AddressListParams.java similarity index 97% rename from src/main/bookingbugAPI/models/params/AddressListParams.java rename to src/main/bookingbugAPI2/models/params/AddressListParams.java index 1d4de50..5434b35 100644 --- a/src/main/bookingbugAPI/models/params/AddressListParams.java +++ b/src/main/bookingbugAPI2/models/params/AddressListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI2/models/params/AddressParams.java b/src/main/bookingbugAPI2/models/params/AddressParams.java new file mode 100644 index 0000000..a0e9123 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/AddressParams.java @@ -0,0 +1,152 @@ +package bookingbugAPI2.models.params; + + +public class AddressParams { + public static class Create extends Params { + + String address1; + String address2; + String address3; + String address4; + String address5; + String postcode; + String country; + + public String getAddress1() { + return address1; + } + + public Create setAddress1(String address1) { + this.address1 = address1; + return this; + } + + public String getAddress2() { + return address2; + } + + public Create setAddress2(String address2) { + this.address2 = address2; + return this; + } + + public String getAddress3() { + return address3; + } + + public Create setAddress3(String address3) { + this.address3 = address3; + return this; + } + + public String getAddress4() { + return address4; + } + + public Create setAddress4(String address4) { + this.address4 = address4; + return this; + } + + public String getAddress5() { + return address5; + } + + public Create setAddress5(String address5) { + this.address5 = address5; + return this; + } + + public String getPostcode() { + return postcode; + } + + public Create setPostcode(String postcode) { + this.postcode = postcode; + return this; + } + + public String getCountry() { + return country; + } + + public Create setCountry(String country) { + this.country = country; + return this; + } + } + + public static class Update extends Params { + + String address1; + String address2; + String address3; + String address4; + String address5; + String postcode; + String country; + + public String getAddress1() { + return address1; + } + + public Update setAddress1(String address1) { + this.address1 = address1; + return this; + } + + public String getAddress2() { + return address2; + } + + public Update setAddress2(String address2) { + this.address2 = address2; + return this; + } + + public String getAddress3() { + return address3; + } + + public Update setAddress3(String address3) { + this.address3 = address3; + return this; + } + + public String getAddress4() { + return address4; + } + + public Update setAddress4(String address4) { + this.address4 = address4; + return this; + } + + public String getAddress5() { + return address5; + } + + public Update setAddress5(String address5) { + this.address5 = address5; + return this; + } + + public String getPostcode() { + return postcode; + } + + public Update setPostcode(String postcode) { + this.postcode = postcode; + return this; + } + + public String getCountry() { + return country; + } + + public Update setCountry(String country) { + this.country = country; + return this; + } + } +} diff --git a/src/main/bookingbugAPI2/models/params/AdministratorParams.java b/src/main/bookingbugAPI2/models/params/AdministratorParams.java new file mode 100644 index 0000000..47af0fc --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/AdministratorParams.java @@ -0,0 +1,112 @@ +package bookingbugAPI2.models.params; + +public class AdministratorParams { + public static class Create extends Params { + + String name; + String role; + Integer serviceId; + Integer resourceId; + Integer personId; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public String getRole() { + return role; + } + + public Create setRole(String role) { + this.role = role; + return this; + } + + public Integer getServiceId() { + return serviceId; + } + + public Create setServiceId(Integer serviceId) { + this.serviceId = serviceId; + return this; + } + + public Integer getResourceId() { + return resourceId; + } + + public Create setResourceId(Integer resourceId) { + this.resourceId = resourceId; + return this; + } + + public Integer getPersonId() { + return personId; + } + + public Create setPersonId(Integer personId) { + this.personId = personId; + return this; + } + } + + public static class Update extends Params { + + String name; + String role; + Integer serviceId; + Integer resourceId; + Integer personId; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public String getRole() { + return role; + } + + public Update setRole(String role) { + this.role = role; + return this; + } + + public Integer getServiceId() { + return serviceId; + } + + public Update setServiceId(Integer serviceId) { + this.serviceId = serviceId; + return this; + } + + public Integer getResourceId() { + return resourceId; + } + + public Update setResourceId(Integer resourceId) { + this.resourceId = resourceId; + return this; + } + + public Integer getPersonId() { + return personId; + } + + public Update setPersonId(Integer personId) { + this.personId = personId; + return this; + } + } +} + diff --git a/src/main/bookingbugAPI/models/params/BookableItemListParams.java b/src/main/bookingbugAPI2/models/params/BookableItemListParams.java similarity index 96% rename from src/main/bookingbugAPI/models/params/BookableItemListParams.java rename to src/main/bookingbugAPI2/models/params/BookableItemListParams.java index a3c96c9..0f0e777 100644 --- a/src/main/bookingbugAPI/models/params/BookableItemListParams.java +++ b/src/main/bookingbugAPI2/models/params/BookableItemListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/params/BookingCancelParams.java b/src/main/bookingbugAPI2/models/params/BookingCancelParams.java similarity index 83% rename from src/main/bookingbugAPI/models/params/BookingCancelParams.java rename to src/main/bookingbugAPI2/models/params/BookingCancelParams.java index 9928237..96c5c15 100644 --- a/src/main/bookingbugAPI/models/params/BookingCancelParams.java +++ b/src/main/bookingbugAPI2/models/params/BookingCancelParams.java @@ -1,7 +1,4 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; +package bookingbugAPI2.models.params; public class BookingCancelParams extends Params { diff --git a/src/main/bookingbugAPI/models/params/BookingCreateParams.java b/src/main/bookingbugAPI2/models/params/BookingCreateParams.java similarity index 95% rename from src/main/bookingbugAPI/models/params/BookingCreateParams.java rename to src/main/bookingbugAPI2/models/params/BookingCreateParams.java index 01ce2e0..fd28883 100644 --- a/src/main/bookingbugAPI/models/params/BookingCreateParams.java +++ b/src/main/bookingbugAPI2/models/params/BookingCreateParams.java @@ -1,6 +1,5 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; -import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/params/BookingListParams.java b/src/main/bookingbugAPI2/models/params/BookingListParams.java similarity index 96% rename from src/main/bookingbugAPI/models/params/BookingListParams.java rename to src/main/bookingbugAPI2/models/params/BookingListParams.java index 6646a80..04456a6 100644 --- a/src/main/bookingbugAPI/models/params/BookingListParams.java +++ b/src/main/bookingbugAPI2/models/params/BookingListParams.java @@ -1,7 +1,4 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; +package bookingbugAPI2.models.params; public class BookingListParams extends Params { diff --git a/src/main/bookingbugAPI2/models/params/BookingParams.java b/src/main/bookingbugAPI2/models/params/BookingParams.java new file mode 100644 index 0000000..8ce92e8 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/BookingParams.java @@ -0,0 +1,319 @@ +package bookingbugAPI2.models.params; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +import java.util.Map; + +/** + * Created by sebi on 29.08.2016. + */ +public class BookingParams { + + public static class List extends Params { + String start_date; + String end_date; + String include_cancelled; + String event_id; + String category_id; + String start_time; + String modified_since; + String created_since; + String email; + String client_id; + String order_by; + + public List(int page) { + super(page); + } + + public List(int page, int per_page) { + super(page, per_page); + } + + public DateTime getStart_date() { + return new DateTime(start_date); + } + + public List setStart_date(DateTime start_date) { + this.start_date = ISODateTimeFormat.dateTime().print(start_date); + + return this; + } + + public DateTime getEnd_date() { + return new DateTime(end_date); + } + + public List setEnd_date(DateTime end_date) { + this.end_date = ISODateTimeFormat.dateTime().print(end_date); + return this; + } + + public Boolean getInclude_cancelled() { + return Boolean.valueOf(include_cancelled); + } + + public List setInclude_cancelled(Boolean include_cancelled) { + this.include_cancelled = include_cancelled.toString(); + return this; + } + + public Integer getEvent_id() { + return Integer.valueOf(event_id); + } + + public List setEvent_id(Integer event_id) { + this.event_id = event_id.toString(); + return this; + } + + public Integer getCategory_id() { + return Integer.valueOf(category_id); + } + + public List setCategory_id(Integer category_id) { + this.category_id = category_id.toString(); + return this; + } + + public DateTime getStart_time() { + return new DateTime(start_time); + } + + public List setStart_time(DateTime start_time) { + this.start_time = ISODateTimeFormat.dateTime().print(start_time); + return this; + } + + public DateTime getModified_since() { + return new DateTime(modified_since); + } + + public List setModified_since(DateTime modified_since) { + this.modified_since = ISODateTimeFormat.dateTime().print(modified_since); + return this; + } + + public DateTime getCreated_since() { + return new DateTime(created_since); + } + + public List setCreated_since(DateTime created_since) { + this.created_since = ISODateTimeFormat.dateTime().print(created_since); + return this; + } + + public String getEmail() { + return email; + } + + public List setEmail(String email) { + this.email = email; + return this; + } + + public Integer getClient_id() { + return Integer.valueOf(client_id); + } + + public List setClient_id(Integer client_id) { + this.client_id = client_id.toString(); + return this; + } + + public String getOrder_by() { + return order_by; + } + + public List setOrder_by(String order_by) { + this.order_by = order_by; + return this; + } + } + + public static class Create extends Params { + String datetime; + String service_id; + String person_id; + String resource_id; + String member_id; + String notifications; + + public DateTime getDatetime() { + return new DateTime(datetime); + } + + + public String getService_id() { + return service_id; + } + + + + public String getPerson_id() { + return person_id; + } + + + public String getResource_id() { + return resource_id; + } + + + public String getMember_id() { + return member_id; + } + + + public Boolean getNotifications() { + return Boolean.valueOf(notifications); + } + + public Create setDatetime(DateTime datetime) { + this.datetime = ISODateTimeFormat.dateTime().print(datetime); + return this; + } + + public Create setService_id(String service_id) { + this.service_id = service_id; + return this; + } + + public Create setPerson_id(String person_id) { + this.person_id = person_id; + return this; + } + + public Create setResource_id(String resource_id) { + this.resource_id = resource_id; + return this; + } + + public Create setMember_id(String member_id) { + this.member_id = member_id; + return this; + } + + public Create setNotifications(Boolean notifications) { + this.notifications = notifications.toString(); + return this; + } + } + + public static class Update extends Params { + String datetime; + String duration; + String person_id; + String resource_id; + String email; + String email_owner; + String client_name; + String client_email; + String status; + + public DateTime getDatetime() { + return new DateTime(datetime); + } + + public String getPerson_id() { + return person_id; + } + + public String getResource_id() { + return resource_id; + } + + public Update setDatetime(DateTime datetime) { + this.datetime = ISODateTimeFormat.dateTime().print(datetime); + return this; + } + + public Integer getDuration() { + return Integer.valueOf(duration); + } + + public Update setDuration(Integer duration) { + this.duration = duration.toString(); + return this; + } + + public Update setPerson_id(String person_id) { + this.person_id = person_id; + return this; + } + + public Update setResource_id(String resource_id) { + this.resource_id = resource_id; + return this; + } + + public String getEmail() { + return email; + } + + public Update setEmail(String email) { + this.email = email; + return this; + } + + public String getEmail_owner() { + return email_owner; + } + + public Update setEmail_owner(String email_owner) { + this.email_owner = email_owner; + return this; + } + + public String getClient_name() { + return client_name; + } + + public Update setClient_name(String client_name) { + this.client_name = client_name; + return this; + } + + public String getClient_email() { + return client_email; + } + + public Update setClient_email(String client_email) { + this.client_email = client_email; + return this; + } + + public String getStatus() { + return status; + } + + public Update setStatus(String status) { + this.status = status; + return this; + } + } + + public static class Cancel extends Params { + String notify = "true"; + String cancel_reason; + + public Boolean getNotify() { + return Boolean.valueOf(notify); + } + + public Cancel setNotify(Boolean notify) { + this.notify = notify.toString(); + return this; + } + + public String getCancelReason() { + return cancel_reason; + } + + public Cancel setCancelReason(String cancel_reason) { + this.cancel_reason = cancel_reason; + return this; + } + } +} diff --git a/src/main/bookingbugAPI/models/params/BookingUpdateParams.java b/src/main/bookingbugAPI2/models/params/BookingUpdateParams.java similarity index 98% rename from src/main/bookingbugAPI/models/params/BookingUpdateParams.java rename to src/main/bookingbugAPI2/models/params/BookingUpdateParams.java index 9004e4e..57a187d 100644 --- a/src/main/bookingbugAPI/models/params/BookingUpdateParams.java +++ b/src/main/bookingbugAPI2/models/params/BookingUpdateParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/params/ClientCreateParams.java b/src/main/bookingbugAPI2/models/params/ClientCreateParams.java similarity index 98% rename from src/main/bookingbugAPI/models/params/ClientCreateParams.java rename to src/main/bookingbugAPI2/models/params/ClientCreateParams.java index b3e14be..a57d6a0 100644 --- a/src/main/bookingbugAPI/models/params/ClientCreateParams.java +++ b/src/main/bookingbugAPI2/models/params/ClientCreateParams.java @@ -1,10 +1,11 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.Map; /** * Created by sebi on 18.01.2016. */ +@Deprecated public class ClientCreateParams extends Params { String first_name; diff --git a/src/main/bookingbugAPI2/models/params/ClientListParams.java b/src/main/bookingbugAPI2/models/params/ClientListParams.java new file mode 100644 index 0000000..a26cd64 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ClientListParams.java @@ -0,0 +1,128 @@ +package bookingbugAPI2.models.params; + +import java.util.HashMap; +import java.util.Map; + + +public class ClientListParams { + String page; + String per_page; + String filter_by; + String filter_by_fields; + String order_by; + String order_by_reverse; + + public ClientListParams() { + } + + public ClientListParams(Map args) { + if (args == null || args.isEmpty()) { + return; + } + + String strValue; + + for (Map.Entry entry : args.entrySet()) { + final String[] value = entry.getValue(); + if (value[0] != null && !value[0].trim().isEmpty()) { + strValue = null; + } else { + strValue = value[0]; + } + + switch (entry.getKey()) { + case "page": + page = strValue; + break; + case "per_page": + per_page = strValue; + break; + case "filter_by": + filter_by = strValue; + break; + case "filter_by_fields": + filter_by_fields = strValue; + break; + case "order_by": + order_by = strValue; + break; + case "order_by_reverse": + order_by_reverse = strValue; + break; + } + } + } + + + /** + * getParams + * + * @return Map + */ + public Map getParams() { + Map params = new HashMap<>(); + + params.put("page", page); + params.put("per_page", per_page); + params.put("filter_by", filter_by); + params.put("filter_by_fields", filter_by_fields); + params.put("order_by", order_by); + params.put("order_by_reverse", order_by_reverse); + + return params; + } + + public String getPage() { + return page; + } + + public ClientListParams setPage(String page) { + this.page = page; + return this; + } + + public String getPer_page() { + return per_page; + } + + public ClientListParams setPer_page(String per_page) { + this.per_page = per_page; + return this; + } + + public String getFilterBy() { + return filter_by; + } + + public ClientListParams setFilterBy(String filter_by) { + this.filter_by = filter_by; + return this; + } + + public String getFilterByFields() { + return filter_by_fields; + } + + public ClientListParams setFilterByFields(String filter_by_fields) { + this.filter_by_fields = filter_by_fields; + return this; + } + + public String getOrderBy() { + return order_by; + } + + public ClientListParams setOrderBy(String order_by) { + this.order_by = order_by; + return this; + } + + public String getOrderByReverse() { + return order_by_reverse; + } + + public ClientListParams setOrderByReverse(String order_by_reverse) { + this.order_by_reverse = order_by_reverse; + return this; + } +} diff --git a/src/main/bookingbugAPI2/models/params/ClientParams.java b/src/main/bookingbugAPI2/models/params/ClientParams.java new file mode 100644 index 0000000..2f7cd89 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ClientParams.java @@ -0,0 +1,306 @@ +package bookingbugAPI2.models.params; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +/** + * Created by sebi on 21.06.2016. + */ +public class ClientParams { + + public static class Create extends Params { + String first_name; + String last_name; + String email; + String mobile; + String address1; + String address2; + String address3; + String address4; + String address5; + String postcode; + String reference; + String member_type; + String country; + String send_email; + String member_level_id; + + public String getFirst_name() { + return first_name; + } + + public Create setFirst_name(String first_name) { + this.first_name = first_name; + return this; + } + + public String getLast_name() { + return last_name; + } + + public Create setLast_name(String last_name) { + this.last_name = last_name; + return this; + } + + public String getEmail() { + return email; + } + + public Create setEmail(String email) { + this.email = email; + return this; + } + + public String getMobile() { + return mobile; + } + + public Create setMobile(String mobile) { + this.mobile = mobile; + return this; + } + + public String getAddress1() { + return address1; + } + + public Create setAddress1(String address1) { + this.address1 = address1; + return this; + } + + public String getAddress2() { + return address2; + } + + public Create setAddress2(String address2) { + this.address2 = address2; + return this; + } + + public String getAddress3() { + return address3; + } + + public Create setAddress3(String address3) { + this.address3 = address3; + return this; + } + + public String getAddress4() { + return address4; + } + + public Create setAddress4(String address4) { + this.address4 = address4; + return this; + } + + public String getAddress5() { + return address5; + } + + public Create setAddress5(String address5) { + this.address5 = address5; + return this; + } + + public String getPostcode() { + return postcode; + } + + public Create setPostcode(String postcode) { + this.postcode = postcode; + return this; + } + + public String getReference() { + return reference; + } + + public Create setReference(String reference) { + this.reference = reference; + return this; + } + + public String getMember_type() { + return member_type; + } + + public Create setMember_type(String member_type) { + this.member_type = member_type; + return this; + } + + public String getCountry() { + return country; + } + + public Create setCountry(String country) { + this.country = country; + return this; + } + + public String getSend_email() { + return send_email; + } + + public Create setSend_email(String send_email) { + this.send_email = send_email; + return this; + } + + public String getMember_level_id() { + return member_level_id; + } + + public Create setMember_level_id(String member_level_id) { + this.member_level_id = member_level_id; + return this; + } + } + + public static class Update extends Params { + String first_name; + String last_name; + String email; + String mobile; + String address1; + String address2; + String address3; + String address4; + String address5; + String postcode; + String reference; + String join_date; + String country; + String member_level_id; + + public String getFirst_name() { + return first_name; + } + + public Update setFirst_name(String first_name) { + this.first_name = first_name; + return this; + } + + public String getLast_name() { + return last_name; + } + + public Update setLast_name(String last_name) { + this.last_name = last_name; + return this; + } + + public String getEmail() { + return email; + } + + public Update setEmail(String email) { + this.email = email; + return this; + } + + public String getMobile() { + return mobile; + } + + public Update setMobile(String mobile) { + this.mobile = mobile; + return this; + } + + public String getAddress1() { + return address1; + } + + public Update setAddress1(String address1) { + this.address1 = address1; + return this; + } + + public String getAddress2() { + return address2; + } + + public Update setAddress2(String address2) { + this.address2 = address2; + return this; + } + + public String getAddress3() { + return address3; + } + + public Update setAddress3(String address3) { + this.address3 = address3; + return this; + } + + public String getAddress4() { + return address4; + } + + public Update setAddress4(String address4) { + this.address4 = address4; + return this; + } + + public String getAddress5() { + return address5; + } + + public Update setAddress5(String address5) { + this.address5 = address5; + return this; + } + + public String getPostcode() { + return postcode; + } + + public Update setPostcode(String postcode) { + this.postcode = postcode; + return this; + } + + public String getReference() { + return reference; + } + + public Update setReference(String reference) { + this.reference = reference; + return this; + } + + public DateTime getJoin_date() { + return new DateTime(join_date); + } + + public Update setJoin_date(DateTime join_date) { + this.join_date = ISODateTimeFormat.dateTime().print(join_date); + return this; + } + + public String getCountry() { + return country; + } + + public Update setCountry(String country) { + this.country = country; + return this; + } + + public String getMember_level_id() { + return member_level_id; + } + + public Update setMember_level_id(String member_level_id) { + this.member_level_id = member_level_id; + return this; + } + } +} diff --git a/src/main/bookingbugAPI/models/params/ClientReadEmailParams.java b/src/main/bookingbugAPI2/models/params/ClientReadEmailParams.java similarity index 96% rename from src/main/bookingbugAPI/models/params/ClientReadEmailParams.java rename to src/main/bookingbugAPI2/models/params/ClientReadEmailParams.java index 7769bf1..402fc5a 100644 --- a/src/main/bookingbugAPI/models/params/ClientReadEmailParams.java +++ b/src/main/bookingbugAPI2/models/params/ClientReadEmailParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/params/ClientReadRefParams.java b/src/main/bookingbugAPI2/models/params/ClientReadRefParams.java similarity index 97% rename from src/main/bookingbugAPI/models/params/ClientReadRefParams.java rename to src/main/bookingbugAPI2/models/params/ClientReadRefParams.java index f579873..d3ffba5 100644 --- a/src/main/bookingbugAPI/models/params/ClientReadRefParams.java +++ b/src/main/bookingbugAPI2/models/params/ClientReadRefParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI2/models/params/ClientToggleParams.java b/src/main/bookingbugAPI2/models/params/ClientToggleParams.java new file mode 100644 index 0000000..1bf2883 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ClientToggleParams.java @@ -0,0 +1,38 @@ +package bookingbugAPI2.models.params; + +/** + * Created by sebi on 21.06.2016. + */ +public class ClientToggleParams extends Params { + + String id; + String email; + boolean disabled; + + public String getId() { + return id; + } + + public ClientToggleParams setId(String id) { + this.id = id; + return this; + } + + public String getEmail() { + return email; + } + + public ClientToggleParams setEmail(String email) { + this.email = email; + return this; + } + + public boolean isDisabled() { + return disabled; + } + + public ClientToggleParams setDisabled(boolean disabled) { + this.disabled = disabled; + return this; + } +} diff --git a/src/main/bookingbugAPI2/models/params/ClinicParams.java b/src/main/bookingbugAPI2/models/params/ClinicParams.java new file mode 100644 index 0000000..3f0728a --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ClinicParams.java @@ -0,0 +1,74 @@ +package bookingbugAPI2.models.params; + +import org.joda.time.DateTime; + + +public class ClinicParams { + public static class Create extends Params { + String name; + DateTime startTime; + DateTime endTime; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public DateTime getStartTime() { + return startTime; + } + + public Create setStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + + public DateTime getEndTime() { + return endTime; + } + + public Create setEndTime(DateTime endTime) { + this.endTime = endTime; + return this; + } + } + + public static class Update extends Params { + + String name; + DateTime startTime; + DateTime endTime; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public DateTime getStartTime() { + return startTime; + } + + public Update setStartTime(DateTime startTime) { + this.startTime = startTime; + return this; + } + + public DateTime getEndTime() { + return endTime; + } + + public Update setEndTime(DateTime endTime) { + this.endTime = endTime; + return this; + } + + } +} diff --git a/src/main/bookingbugAPI2/models/params/CompanyParams.java b/src/main/bookingbugAPI2/models/params/CompanyParams.java new file mode 100644 index 0000000..3a34663 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/CompanyParams.java @@ -0,0 +1,112 @@ +package bookingbugAPI2.models.params; + +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; + +/** + * Created by sebi on 29.08.2016. + */ +public class CompanyParams { + + public static class EventList extends Params { + String start_date; + String end_date; + String resource_id; + String person_id; + String event_group_id; + String event_chain_id; + String summary; + String member_level_id; + Boolean embed; + Boolean include_non_bookable; + String modified_since; + + public DateTime getStart_date() { + return new DateTime(start_date); + } + + public void setStart_date(DateTime start_date) { + this.start_date = ISODateTimeFormat.dateTime().print(start_date); + } + + public DateTime getEnd_date() { + return new DateTime(end_date); + } + + public void setEnd_date(DateTime end_date) { + this.end_date = ISODateTimeFormat.dateTime().print(end_date); + } + + public String getResource_id() { + return resource_id; + } + + public void setResource_id(String resource_id) { + this.resource_id = resource_id; + } + + public String getPerson_id() { + return person_id; + } + + public void setPerson_id(String person_id) { + this.person_id = person_id; + } + + public String getEvent_group_id() { + return event_group_id; + } + + public void setEvent_group_id(String event_group_id) { + this.event_group_id = event_group_id; + } + + public String getEvent_chain_id() { + return event_chain_id; + } + + public void setEvent_chain_id(String event_chain_id) { + this.event_chain_id = event_chain_id; + } + + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + public String getMember_level_id() { + return member_level_id; + } + + public void setMember_level_id(String member_level_id) { + this.member_level_id = member_level_id; + } + + public Boolean getEmbed() { + return embed; + } + + public void setEmbed(Boolean embed) { + this.embed = embed; + } + + public Boolean getInclude_non_bookable() { + return include_non_bookable; + } + + public void setInclude_non_bookable(Boolean include_non_bookable) { + this.include_non_bookable = include_non_bookable; + } + + public DateTime getModified_since() { + return new DateTime(modified_since); + } + + public void setModified_since(DateTime modified_since) { + this.modified_since = ISODateTimeFormat.dateTime().print(modified_since); + } + } +} diff --git a/src/main/bookingbugAPI2/models/params/EventChainParams.java b/src/main/bookingbugAPI2/models/params/EventChainParams.java new file mode 100644 index 0000000..34998e8 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/EventChainParams.java @@ -0,0 +1,262 @@ +package bookingbugAPI2.models.params; + + +public class EventChainParams { + + + public static class Create extends Params { + String name; + String description; + String longDescription; + Integer spaces; + Integer resourceId; + Integer eventGroupId; + Integer duration; + String datetime; + Integer price; + String ticketType; + Integer addressId; + String reference; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Create setDescription(String description) { + this.description = description; + return this; + } + + public String getLongDescription() { + return longDescription; + } + + public Create setLongDescription(String longDescription) { + this.longDescription = longDescription; + return this; + } + + public Integer getSpaces() { + return spaces; + } + + public Create setSpaces(Integer spaces) { + this.spaces = spaces; + return this; + } + + public Integer getResourceId() { + return resourceId; + } + + public Create setResourceId(Integer resourceId) { + this.resourceId = resourceId; + return this; + } + + public Integer getEventGroupId() { + return eventGroupId; + } + + public Create setEventGroupId(Integer eventGroupId) { + this.eventGroupId = eventGroupId; + return this; + } + + public Integer getDuration() { + return duration; + } + + public Create setDuration(Integer duration) { + this.duration = duration; + return this; + } + + public String getDatetime() { + return datetime; + } + + public Create setDatetime(String datetime) { + this.datetime = datetime; + return this; + } + + public Integer getPrice() { + return price; + } + + public Create setPrice(Integer price) { + this.price = price; + return this; + } + + public String getTicketType() { + return ticketType; + } + + public Create setTicketType(String ticketType) { + this.ticketType = ticketType; + return this; + } + + public Integer getAddressId() { + return addressId; + } + + public Create setAddressId(Integer addressId) { + this.addressId = addressId; + return this; + } + + public String getReference() { + return reference; + } + + public Create setReference(String reference) { + this.reference = reference; + return this; + } + } + + public static class Update extends Params { + + String name; + String description; + String longDescription; + Integer spaces; + Integer resourceId; + Integer personId; + Integer eventGroupId; + Integer duration; + String datetime; + Integer price; + String ticketType; + Integer addressId; + String reference; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Update setDescription(String description) { + this.description = description; + return this; + } + + public String getLongDescription() { + return longDescription; + } + + public Update setLongDescription(String longDescription) { + this.longDescription = longDescription; + return this; + } + + public Integer getSpaces() { + return spaces; + } + + public Update setSpaces(Integer spaces) { + this.spaces = spaces; + return this; + } + + public Integer getResourceId() { + return resourceId; + } + + public Integer getPersonId() { + return personId; + } + + public void setPersonId(Integer personId) { + this.personId = personId; + } + + public Update setResourceId(Integer resourceId) { + this.resourceId = resourceId; + return this; + } + + public Integer getEventGroupId() { + return eventGroupId; + } + + public Update setEventGroupId(Integer eventGroupId) { + this.eventGroupId = eventGroupId; + return this; + } + + public Integer getDuration() { + return duration; + } + + public Update setDuration(Integer duration) { + this.duration = duration; + return this; + } + + public String getDatetime() { + return datetime; + } + + public Update setDatetime(String datetime) { + this.datetime = datetime; + return this; + } + + public Integer getPrice() { + return price; + } + + public Update setPrice(Integer price) { + this.price = price; + return this; + } + + public String getTicketType() { + return ticketType; + } + + public Update setTicketType(String ticketType) { + this.ticketType = ticketType; + return this; + } + + public Integer getAddressId() { + return addressId; + } + + public Update setAddressId(Integer addressId) { + this.addressId = addressId; + return this; + } + + public String getReference() { + return reference; + } + + public Update setReference(String reference) { + this.reference = reference; + return this; + } + } +} diff --git a/src/main/bookingbugAPI/models/params/EventListParams.java b/src/main/bookingbugAPI2/models/params/EventListParams.java similarity index 97% rename from src/main/bookingbugAPI/models/params/EventListParams.java rename to src/main/bookingbugAPI2/models/params/EventListParams.java index 48ed147..8ec1dfb 100644 --- a/src/main/bookingbugAPI/models/params/EventListParams.java +++ b/src/main/bookingbugAPI2/models/params/EventListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; /** * Created by sebi on 31.03.2016. diff --git a/src/main/bookingbugAPI/models/params/Params.java b/src/main/bookingbugAPI2/models/params/Params.java similarity index 96% rename from src/main/bookingbugAPI/models/params/Params.java rename to src/main/bookingbugAPI2/models/params/Params.java index b85b212..6609aba 100644 --- a/src/main/bookingbugAPI/models/params/Params.java +++ b/src/main/bookingbugAPI2/models/params/Params.java @@ -1,12 +1,10 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; @@ -24,6 +22,11 @@ public Params(int page) { this.page = page; } + public Params(int page, int per_page) { + this.page = page; + this.per_page = per_page; + } + public Params(Map args){ setNotNullStringMap(args); } diff --git a/src/main/bookingbugAPI/models/params/PeopleListParams.java b/src/main/bookingbugAPI2/models/params/PersonListParams.java similarity index 89% rename from src/main/bookingbugAPI/models/params/PeopleListParams.java rename to src/main/bookingbugAPI2/models/params/PersonListParams.java index bf72b12..e66b5bb 100644 --- a/src/main/bookingbugAPI/models/params/PeopleListParams.java +++ b/src/main/bookingbugAPI2/models/params/PersonListParams.java @@ -1,19 +1,19 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; -public class PeopleListParams { +public class PersonListParams { String page; String per_page; - public PeopleListParams(){} + public PersonListParams(){} - public PeopleListParams(Map args){ + public PersonListParams(Map args){ if (args==null || args.isEmpty()) { return; } diff --git a/src/main/bookingbugAPI2/models/params/PersonParams.java b/src/main/bookingbugAPI2/models/params/PersonParams.java new file mode 100644 index 0000000..c9674af --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/PersonParams.java @@ -0,0 +1,170 @@ +package bookingbugAPI2.models.params; + + +public class PersonParams { + public static class Create extends Params { + String name; + String description; + String email; + String phonePrefix; + String phone; + String icalLink; + Boolean neverBooked; + Boolean notify; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Create setDescription(String description) { + this.description = description; + return this; + } + + public String getEmail() { + return email; + } + + public Create setEmail(String email) { + this.email = email; + return this; + } + + public String getPhonePrefix() { + return phonePrefix; + } + + public Create setPhonePrefix(String phonePrefix) { + this.phonePrefix = phonePrefix; + return this; + } + + public String getPhone() { + return phone; + } + + public Create setPhone(String phone) { + this.phone = phone; + return this; + } + + public String getIcalLink() { + return icalLink; + } + + public Create setIcalLink(String icalLink) { + this.icalLink = icalLink; + return this; + } + + public Boolean getNeverBooked() { + return neverBooked; + } + + public Create setNeverBooked(Boolean neverBooked) { + this.neverBooked = neverBooked; + return this; + } + + public Boolean getNotify() { + return notify; + } + + public Create setNotify(Boolean notify) { + this.notify = notify; + return this; + } + } + + public static class Update extends Params { + String name; + String description; + String email; + String phonePrefix; + String phone; + String icalLink; + Boolean neverBooked; + Boolean notify; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Update setDescription(String description) { + this.description = description; + return this; + } + + public String getEmail() { + return email; + } + + public Update setEmail(String email) { + this.email = email; + return this; + } + + public String getPhonePrefix() { + return phonePrefix; + } + + public Update setPhonePrefix(String phonePrefix) { + this.phonePrefix = phonePrefix; + return this; + } + + public String getPhone() { + return phone; + } + + public Update setPhone(String phone) { + this.phone = phone; + return this; + } + + public String getIcalLink() { + return icalLink; + } + + public Update setIcalLink(String icalLink) { + this.icalLink = icalLink; + return this; + } + + public Boolean getNeverBooked() { + return neverBooked; + } + + public Update setNeverBooked(Boolean neverBooked) { + this.neverBooked = neverBooked; + return this; + } + + public Boolean getNotify() { + return notify; + } + + public Update setNotify(Boolean notify) { + this.notify = notify; + return this; + } + } +} diff --git a/src/main/bookingbugAPI2/models/params/PurchaseListParams.java b/src/main/bookingbugAPI2/models/params/PurchaseListParams.java new file mode 100644 index 0000000..c53e961 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/PurchaseListParams.java @@ -0,0 +1,58 @@ +package bookingbugAPI2.models.params; + +import org.joda.time.DateTime; + + +public class PurchaseListParams extends Params{ + + DateTime created_from; + DateTime created_to; + String admin_bookings_only; + String order_by; + String order_by_reverse; + + public DateTime getCreated_from() { + return created_from; + } + + public PurchaseListParams setCreated_from(DateTime created_from) { + this.created_from = created_from; + return this; + } + + public DateTime getCreated_to() { + return created_to; + } + + public PurchaseListParams setCreated_to(DateTime created_to) { + this.created_to = created_to; + return this; + } + + public String getAdmin_bookings_only() { + return admin_bookings_only; + } + + public PurchaseListParams setAdmin_bookings_only(String admin_bookings_only) { + this.admin_bookings_only = admin_bookings_only; + return this; + } + + public String getOrder_by() { + return order_by; + } + + public PurchaseListParams setOrder_by(String order_by) { + this.order_by = order_by; + return this; + } + + public String getOrder_by_reverse() { + return order_by_reverse; + } + + public PurchaseListParams setOrder_by_reverse(String order_by_reverse) { + this.order_by_reverse = order_by_reverse; + return this; + } +} diff --git a/src/main/bookingbugAPI2/models/params/PurchaseParams.java b/src/main/bookingbugAPI2/models/params/PurchaseParams.java new file mode 100644 index 0000000..ec1174c --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/PurchaseParams.java @@ -0,0 +1,75 @@ +package bookingbugAPI2.models.params; + + +public class PurchaseParams extends Params{ + Integer amount; + String notes; + String paymentStatus; + String transactionId; + Boolean notify; + Boolean notifyAdmin; + Integer paymentType; + + public Integer getAmount() { + return amount; + } + + public PurchaseParams setAmount(Integer amount) { + this.amount = amount; + return this; + } + + public String getNotes() { + return notes; + } + + public PurchaseParams setNotes(String notes) { + this.notes = notes; + return this; + } + + public String getPaymentStatus() { + return paymentStatus; + } + + public PurchaseParams setPaymentStatus(String paymentStatus) { + this.paymentStatus = paymentStatus; + return this; + } + + public String getTransactionId() { + return transactionId; + } + + public PurchaseParams setTransactionId(String transactionId) { + this.transactionId = transactionId; + return this; + } + + public Boolean getNotify() { + return notify; + } + + public PurchaseParams setNotify(Boolean notify) { + this.notify = notify; + return this; + } + + public Boolean getNotifyAdmin() { + return notifyAdmin; + } + + public PurchaseParams setNotifyAdmin(Boolean notifyAdmin) { + this.notifyAdmin = notifyAdmin; + return this; + } + + public Integer getPaymentType() { + return paymentType; + } + + public PurchaseParams setPaymentType(Integer paymentType) { + this.paymentType = paymentType; + return this; + } +} diff --git a/src/main/bookingbugAPI2/models/params/QuestionListParams.java b/src/main/bookingbugAPI2/models/params/QuestionListParams.java new file mode 100644 index 0000000..31818db --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/QuestionListParams.java @@ -0,0 +1,16 @@ +package bookingbugAPI2.models.params; + + +public class QuestionListParams extends Params { + + String detail_group_id; + + public String getDetail_group_id() { + return detail_group_id; + } + + public QuestionListParams setDetail_group_id(String detail_group_id) { + this.detail_group_id = detail_group_id; + return this; + } +} diff --git a/src/main/bookingbugAPI/models/params/ResourceListParams.java b/src/main/bookingbugAPI2/models/params/ResourceListParams.java similarity index 97% rename from src/main/bookingbugAPI/models/params/ResourceListParams.java rename to src/main/bookingbugAPI2/models/params/ResourceListParams.java index 029d9f0..2d9cfd5 100644 --- a/src/main/bookingbugAPI/models/params/ResourceListParams.java +++ b/src/main/bookingbugAPI2/models/params/ResourceListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI2/models/params/ResourceParams.java b/src/main/bookingbugAPI2/models/params/ResourceParams.java new file mode 100644 index 0000000..7b1b9a0 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ResourceParams.java @@ -0,0 +1,115 @@ +package bookingbugAPI2.models.params; + +/** + * Created by sebi on 27.06.2016. + */ +public class ResourceParams { + + //TODO: Add all fields + public static class Create extends Params { + String name; + String description; + String email; + boolean disabled; + boolean never_booked; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Create setDescription(String description) { + this.description = description; + return this; + } + + public String getEmail() { + return email; + } + + public Create setEmail(String email) { + this.email = email; + return this; + } + + public boolean isDisabled() { + return disabled; + } + + public Create setDisabled(boolean disabled) { + this.disabled = disabled; + return this; + } + + public boolean isNever_booked() { + return never_booked; + } + + public Create setNever_booked(boolean never_booked) { + this.never_booked = never_booked; + return this; + } + } + + //TODO: Add all fields + public static class Update extends Params { + String name; + String description; + String email; + boolean disabled; + boolean never_booked; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public String getDescription() { + return description; + } + + public Update setDescription(String description) { + this.description = description; + return this; + } + + public String getEmail() { + return email; + } + + public Update setEmail(String email) { + this.email = email; + return this; + } + + public boolean isDisabled() { + return disabled; + } + + public Update setDisabled(boolean disabled) { + this.disabled = disabled; + return this; + } + + public boolean isNever_booked() { + return never_booked; + } + + public Update setNever_booked(boolean never_booked) { + this.never_booked = never_booked; + return this; + } + } +} diff --git a/src/main/bookingbugAPI2/models/params/ScheduleParams.java b/src/main/bookingbugAPI2/models/params/ScheduleParams.java new file mode 100644 index 0000000..e111384 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ScheduleParams.java @@ -0,0 +1,71 @@ +package bookingbugAPI2.models.params; + + +public class ScheduleParams { + public static class Create extends Params { + String name; + String desc; + Integer style; + + public String getName() { + return name; + } + + public Create setName(String name) { + this.name = name; + return this; + } + + public String getDesc() { + return desc; + } + + public Create setDesc(String desc) { + this.desc = desc; + return this; + } + + public Integer getStyle() { + return style; + } + + public Create setStyle(Integer style) { + this.style = style; + return this; + } + } + + public static class Update extends Params { + + String name; + String desc; + Integer style; + + public String getName() { + return name; + } + + public Update setName(String name) { + this.name = name; + return this; + } + + public String getDesc() { + return desc; + } + + public Update setDesc(String desc) { + this.desc = desc; + return this; + } + + public Integer getStyle() { + return style; + } + + public Update setStyle(Integer style) { + this.style = style; + return this; + } + } +} diff --git a/src/main/bookingbugAPI/models/params/ServiceListParams.java b/src/main/bookingbugAPI2/models/params/ServiceListParams.java similarity index 66% rename from src/main/bookingbugAPI/models/params/ServiceListParams.java rename to src/main/bookingbugAPI2/models/params/ServiceListParams.java index ad596e4..d6b6f2e 100644 --- a/src/main/bookingbugAPI/models/params/ServiceListParams.java +++ b/src/main/bookingbugAPI2/models/params/ServiceListParams.java @@ -1,7 +1,4 @@ -package bookingbugAPI.models.params; - -import java.util.HashMap; -import java.util.Map; +package bookingbugAPI2.models.params; public class ServiceListParams extends Params{ diff --git a/src/main/bookingbugAPI2/models/params/ServiceParams.java b/src/main/bookingbugAPI2/models/params/ServiceParams.java new file mode 100644 index 0000000..d682d1e --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/ServiceParams.java @@ -0,0 +1,85 @@ +package bookingbugAPI2.models.params; + +/** + * Created by sebi on 16.06.2016. + */ +public class ServiceParams { + + public static class ServiceCreateParams extends Params { + + String name; + String reference; + Integer duration; + Integer spaces; + + public String getName() { + return name; + } + + public ServiceCreateParams setName(String name) { + this.name = name; + return this; + } + + public String getReference() { + return reference; + } + + public ServiceCreateParams setReference(String reference) { + this.reference = reference; + return this; + } + + public Integer getDuration() { + return duration; + } + + public ServiceCreateParams setDuration(Integer duration) { + this.duration = duration; + return this; + } + + public Integer getSpaces() { + return spaces; + } + + public ServiceCreateParams setSpaces(Integer spaces) { + this.spaces = spaces; + return this; + } + } + + public static class ServiceUpdateParams extends Params { + + String name; + String reference; + Integer duration; + + public String getName() { + return name; + } + + public ServiceUpdateParams setName(String name) { + this.name = name; + return this; + } + + public String getReference() { + return reference; + } + + public ServiceUpdateParams setReference(String reference) { + this.reference = reference; + return this; + } + + public Integer getDuration() { + return duration; + } + + public ServiceUpdateParams setDuration(Integer duration) { + this.duration = duration; + return this; + } + } +} diff --git a/src/main/bookingbugAPI/models/params/SessionListParams.java b/src/main/bookingbugAPI2/models/params/SessionListParams.java similarity index 97% rename from src/main/bookingbugAPI/models/params/SessionListParams.java rename to src/main/bookingbugAPI2/models/params/SessionListParams.java index 50746e8..bdac3bc 100644 --- a/src/main/bookingbugAPI/models/params/SessionListParams.java +++ b/src/main/bookingbugAPI2/models/params/SessionListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI/models/params/SlotListParams.java b/src/main/bookingbugAPI2/models/params/SlotListParams.java similarity index 98% rename from src/main/bookingbugAPI/models/params/SlotListParams.java rename to src/main/bookingbugAPI2/models/params/SlotListParams.java index 30e06db..5c7a8c5 100644 --- a/src/main/bookingbugAPI/models/params/SlotListParams.java +++ b/src/main/bookingbugAPI2/models/params/SlotListParams.java @@ -1,4 +1,4 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import java.util.HashMap; import java.util.Map; diff --git a/src/main/bookingbugAPI2/models/params/SlotParams.java b/src/main/bookingbugAPI2/models/params/SlotParams.java new file mode 100644 index 0000000..25339a8 --- /dev/null +++ b/src/main/bookingbugAPI2/models/params/SlotParams.java @@ -0,0 +1,112 @@ +package bookingbugAPI2.models.params; + +public class SlotParams { + public static class Create extends Params { + String startTime; + String endTime; + String allday; + String personId; + String resourceId; + + public String getStartTime() { + return startTime; + } + + public Create setStartTime(String startTime) { + this.startTime = startTime; + return this; + } + + public String getEndTime() { + return endTime; + } + + public Create setEndTime(String endTime) { + this.endTime = endTime; + return this; + } + + public String getAllday() { + return allday; + } + + public Create setAllday(String allday) { + this.allday = allday; + return this; + } + + public String getPersonId() { + return personId; + } + + public Create setPersonId(String personId) { + this.personId = personId; + return this; + } + + public String getResourceId() { + return resourceId; + } + + public Create setResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + } + + public static class Update extends Params { + + String startTime; + String endTime; + String allday; + String personId; + String resourceId; + + public String getStartTime() { + return startTime; + } + + public Update setStartTime(String startTime) { + this.startTime = startTime; + return this; + } + + public String getEndTime() { + return endTime; + } + + public Update setEndTime(String endTime) { + this.endTime = endTime; + return this; + } + + public String getAllday() { + return allday; + } + + public Update setAllday(String allday) { + this.allday = allday; + return this; + } + + public String getPersonId() { + return personId; + } + + public Update setPersonId(String personId) { + this.personId = personId; + return this; + } + + public String getResourceId() { + return resourceId; + } + + public Update setResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + } + +} diff --git a/src/main/bookingbugAPI/models/params/TimeDataParams.java b/src/main/bookingbugAPI2/models/params/TimeDataParams.java similarity index 96% rename from src/main/bookingbugAPI/models/params/TimeDataParams.java rename to src/main/bookingbugAPI2/models/params/TimeDataParams.java index bbfab58..2cfae0c 100644 --- a/src/main/bookingbugAPI/models/params/TimeDataParams.java +++ b/src/main/bookingbugAPI2/models/params/TimeDataParams.java @@ -1,9 +1,7 @@ -package bookingbugAPI.models.params; +package bookingbugAPI2.models.params; import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import javax.print.DocFlavor; -import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Date; import java.util.StringTokenizer; diff --git a/src/main/bookingbugAPI2/services/ConfigService.java b/src/main/bookingbugAPI2/services/ConfigService.java new file mode 100644 index 0000000..229a65b --- /dev/null +++ b/src/main/bookingbugAPI2/services/ConfigService.java @@ -0,0 +1,86 @@ +package bookingbugAPI2.services; + +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.StringReader; +import java.util.Properties; + +/** + * Created by sebi on 07.07.2016. + */ +public class ConfigService { + + static final String propFileName = "bb_sdk_config.properties"; + + public String auth_token; + public String appId; + public String appKey; + public String userAgent; + public String serverUrl; + + public ConfigService(){ + auth_token = null; + appId = ""; + appKey = ""; + userAgent = ""; + serverUrl = null; + } + + public ConfigService(ConfigService configService) { + auth_token = configService.auth_token; + appId = configService.appId; + appKey = configService.appKey; + userAgent = configService.userAgent; + serverUrl = configService.serverUrl; + } + + public ConfigService setAuth_token(String auth_token) { + this.auth_token = auth_token; + return this; + } + + public ConfigService setAppId(String appId) { + this.appId = appId; + return this; + } + + public ConfigService setAppKey(String appKey) { + this.appKey = appKey; + return this; + } + + public ConfigService setUserAgent(String userAgent) { + this.userAgent = userAgent; + return this; + } + + public ConfigService setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + return this; + } + + public void loadConfigFile(String configString) { + try{ + Properties prop = new Properties(); + + if(configString != null) { + prop.load(new StringReader(configString)); + } + else { + InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propFileName); + if (inputStream != null) { + prop.load(inputStream); + } else { + throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); + } + } + + appId = prop.getProperty("application.auth.appid"); + appKey = prop.getProperty("application.auth.appkey"); + userAgent = prop.getProperty("application.auth.useragent"); + serverUrl = prop.getProperty("application.auth.serverurl"); + } catch (Exception e) { + //logger.log(Level.SEVERE, "Exception @ ApiConfig.withConfigFile(): " + e.getMessage()); + } + } +} diff --git a/src/main/bookingbugAPI2/services/ServiceProvider.java b/src/main/bookingbugAPI2/services/ServiceProvider.java new file mode 100644 index 0000000..ac7e31c --- /dev/null +++ b/src/main/bookingbugAPI2/services/ServiceProvider.java @@ -0,0 +1,16 @@ +package bookingbugAPI2.services; + +import bookingbugAPI2.services.cache.AbstractCacheService; +import bookingbugAPI2.services.http.AbstractHttpService; +import bookingbugAPI2.services.logger.AbstractLoggerService; + +/** + * Created by sebi on 07.07.2016. + */ +public interface ServiceProvider { + + AbstractHttpService httpService(); + AbstractLoggerService loggerService(); + AbstractCacheService cacheService(); + ConfigService configService(); +} diff --git a/src/main/bookingbugAPI2/services/cache/AbstractCacheService.java b/src/main/bookingbugAPI2/services/cache/AbstractCacheService.java new file mode 100644 index 0000000..bec013b --- /dev/null +++ b/src/main/bookingbugAPI2/services/cache/AbstractCacheService.java @@ -0,0 +1,40 @@ +package bookingbugAPI2.services.cache; + +import bookingbugAPI2.services.http.PlainHttpService; + +import javax.annotation.Nullable; + +/** + * Class used for caching HTTP Responses + */ +public abstract class AbstractCacheService { + + private boolean oneTimeFresh = false; + protected int expiryDurationSec = 5 * 60; + + public boolean isOneTimeFresh() { + return oneTimeFresh; + } + + public void setOneTimeFresh(boolean oneTimeFresh) { + this.oneTimeFresh = oneTimeFresh; + } + + public int getExpiryDurationSec() { + return expiryDurationSec; + } + + /** + * Sets the expiry duration in seconds. Default is 5 minutes + * @param expiryDurationSec the duration in seconds + */ + public void setExpiryDurationSec(int expiryDurationSec) { + this.expiryDurationSec = expiryDurationSec; + } + + public abstract void storeResult(String url, String method, String resp, @Nullable String CACHE_TAG); + public abstract PlainHttpService.NetResponse getDBResponse(String url, String method); + public abstract void invalidateResult(String url, String method); + public abstract void invalidateResultsByTag(String CACHE_TAG); + +} diff --git a/src/main/bookingbugAPI2/services/cache/MockCacheService.java b/src/main/bookingbugAPI2/services/cache/MockCacheService.java new file mode 100644 index 0000000..0580c03 --- /dev/null +++ b/src/main/bookingbugAPI2/services/cache/MockCacheService.java @@ -0,0 +1,32 @@ +package bookingbugAPI2.services.cache; + +import bookingbugAPI2.services.http.PlainHttpService; + +import javax.annotation.Nullable; + +/** + * Class used for mocking a cache service. + * {@link #getDBResponse(String, String)} always returns null + * {@link #storeResult(String, String, String, String)} does nothing at all + */ +public class MockCacheService extends AbstractCacheService { + @Override + public void storeResult(String url, String method, String resp, @Nullable String CACHE_KEY) { + + } + + @Override + public PlainHttpService.NetResponse getDBResponse(String url, String method) { + return null; + } + + @Override + public void invalidateResult(String url, String method) { + + } + + @Override + public void invalidateResultsByTag(String CACHE_TAG) { + + } +} diff --git a/src/main/bookingbugAPI2/services/cache/SQLiteCacheService.java b/src/main/bookingbugAPI2/services/cache/SQLiteCacheService.java new file mode 100644 index 0000000..47b451b --- /dev/null +++ b/src/main/bookingbugAPI2/services/cache/SQLiteCacheService.java @@ -0,0 +1,182 @@ +package bookingbugAPI2.services.cache; + +import bookingbugAPI2.services.http.PlainHttpService; +import bookingbugAPI2.services.logger.AbstractLoggerService; +import bookingbugAPI2.services.ServiceProvider; +import com.j256.ormlite.dao.Dao; +import com.j256.ormlite.dao.DaoManager; +import com.j256.ormlite.jdbc.JdbcConnectionSource; +import com.j256.ormlite.logger.LocalLog; +import com.j256.ormlite.stmt.QueryBuilder; +import com.j256.ormlite.support.ConnectionSource; +import com.j256.ormlite.table.TableUtils; + +import javax.annotation.Nullable; +import java.sql.SQLException; +import java.util.Calendar; +import java.util.List; + +/** + * Class used for caching HTTP Responses using SQLite db implementation + */ +public class SQLiteCacheService extends AbstractCacheService { + + SQLite db; + ServiceProvider provider; + + static { + //For OrmLite log garbage + System.setProperty(LocalLog.LOCAL_LOG_LEVEL_PROPERTY, "ERROR"); + } + + public SQLiteCacheService(ServiceProvider provider) { + this.db = new JDBC_Sqlite(); + this.provider = provider; + } + + /** + * Constructor for custom SQLite driver implementation. See {@link SQLite} + * @param provider the service provider + * @param db the SQLite implementation + */ + public SQLiteCacheService(ServiceProvider provider, SQLite db) { + this.db = db; + this.provider = provider; + } + + /** + * cache a network result + * @param url the url + * @param method the http method (verb) + * @param resp the response to cache + * @param CACHE_TAG the TAG for cache record + */ + @Override + public void storeResult(String url, String method, String resp, @Nullable String CACHE_TAG) { + Dao respDao; + AbstractLoggerService.Logger logger = provider.loggerService().getLogger(SQLiteCacheService.class.getName()); + try { + logger.v("Caching result for {0} {1}", url, method); + db.createIfNotExists(); + respDao = db.getDao(); + + PlainHttpService.NetResponse response = new PlainHttpService.NetResponse(url, method, resp, CACHE_TAG); + respDao.create(response); + + } catch (SQLException e) { + logger.e(e, "Error when caching result"); + } + } + + /** + * Restore from cache + * @param url the url + * @param method the http method (verb) + * @return The response if found or null + */ + @Override + public PlainHttpService.NetResponse getDBResponse(String url, String method) { + AbstractLoggerService.Logger logger = provider.loggerService().getLogger(SQLiteCacheService.class.getName()); + try { + db.createIfNotExists(); + Dao respDao = db.getDao(); + QueryBuilder builder = respDao.queryBuilder(); + builder.where().eq("url", url).and().eq("method", method); + List responses = respDao.query(builder.prepare()); + if(responses.size() > 0) { + + PlainHttpService.NetResponse response = responses.get(0); + + //Check if response expired or if isFresh() and delete it if true + if( (Calendar.getInstance().getTimeInMillis() - response.getTimestamp().getTime()) / 1000 >= expiryDurationSec || isOneTimeFresh()) { + logger.v("cache for {0} {1} is expired", url, method); + respDao.delete(response); + setOneTimeFresh(false); + } + else { + logger.v("Restoring from cache result for {0} {1}", url, method); + return responses.get(0); + } + } + + } catch (SQLException e) { + logger.e(e, "Error when restoring from cache"); + } + return null; + } + + @Override + public void invalidateResult(String url, String method) { + AbstractLoggerService.Logger logger = provider.loggerService().getLogger(SQLiteCacheService.class.getName()); + try { + db.createIfNotExists(); + Dao respDao = db.getDao(); + QueryBuilder builder = respDao.queryBuilder(); + builder.where().eq("url", url).and().eq("method", method); + List responses = respDao.query(builder.prepare()); + if(responses.size() > 0) { + PlainHttpService.NetResponse response = responses.get(0); + logger.v("cache for {0} {1} invalidated", url, method); + respDao.delete(response); + } + } catch (SQLException e) { + logger.e(e, "Error when invalidating cache"); + } + } + + @Override + public void invalidateResultsByTag(String CACHE_TAG) { + AbstractLoggerService.Logger logger = provider.loggerService().getLogger(SQLiteCacheService.class.getName()); + try { + db.createIfNotExists(); + Dao respDao = db.getDao(); + QueryBuilder builder = respDao.queryBuilder(); + builder.where().eq("CACHE_TAG", CACHE_TAG); + List responses = respDao.query(builder.prepare()); + respDao.delete(responses); + logger.v("Invalidated {0} caches with tag {1}", responses.size(), CACHE_TAG); + } catch (SQLException e) { + logger.e(e, "Error when invalidating cache"); + } + } + + + /** + * Classes should implement this interface to provide proper handling for SQLite db + */ + public interface SQLite { + + Dao getDao() throws SQLException; + ConnectionSource getConnectionSource() throws SQLException; + void createIfNotExists() throws SQLException; + + } + + /** + * Implementation for SQLite with JDBC + */ + public static final class JDBC_Sqlite implements SQLite { + + ConnectionSource connectionSource; + Dao dao; + + @Override + public void createIfNotExists() throws SQLException { + TableUtils.createTableIfNotExists(getConnectionSource(), PlainHttpService.NetResponse.class); + } + + @Override + public Dao getDao() throws SQLException { + if(dao == null) + dao = DaoManager.createDao(getConnectionSource(), PlainHttpService.NetResponse.class); + return dao; + } + + @Override + public ConnectionSource getConnectionSource() throws SQLException { + if(connectionSource == null) + connectionSource = new JdbcConnectionSource("jdbc:sqlite:test.db"); + return connectionSource; + } + } +} diff --git a/src/main/bookingbugAPI2/services/http/AbstractHttpService.java b/src/main/bookingbugAPI2/services/http/AbstractHttpService.java new file mode 100644 index 0000000..f99a58e --- /dev/null +++ b/src/main/bookingbugAPI2/services/http/AbstractHttpService.java @@ -0,0 +1,235 @@ +package bookingbugAPI2.services.http; + +import bookingbugAPI2.models.HttpException; +import bookingbugAPI2.services.ServiceProvider; +import helpers2.Http; +import helpers2.HttpServiceResponse; + +import javax.annotation.Nullable; +import java.net.URL; +import java.util.Map; + +/** + * Created by sebi on 15.06.2016. + */ +public abstract class AbstractHttpService { + protected final ServiceProvider provider; + + public AbstractHttpService(ServiceProvider provider) { + this.provider = provider; + } + + /** + * Makes a synchronous GET request + * @param url URL to get + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_GET(URL url) throws HttpException { + return callApi(url, "GET", PlainHttpService.urlEncodedContentType, null, null); + } + + /** + * Makes a synchronous GET request + * @param url URL to get + * @param CACHE_TAG the TAG for cache record + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_GET(URL url, String CACHE_TAG) throws HttpException { + return callApi(url, "GET", PlainHttpService.urlEncodedContentType, null, CACHE_TAG); + } + + + /** + * Makes a synchronous POST request with {@link Http#urlEncodedContentType} contentType + * @param url URL to post to + * @param params Map, a generic Map containing data to post + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_POST(URL url, Map params) throws HttpException { + return callApi(url, "POST", PlainHttpService.urlEncodedContentType, params, null); + } + + /** + * Makes a synchronous POST request with {@link Http#urlEncodedContentType} contentType. + * Will invalidate all caches with {@code tag} if not null + * @param url URL to post to + * @param params Map, a generic Map containing data to post + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_POST(URL url, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "POST", PlainHttpService.urlEncodedContentType, params, CACHE_TAG); + } + + + /** + * Makes a synchronous POST request with specific contentType + * @param url URL to post to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to post + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_POST(URL url, String contentType, Map params) throws HttpException { + return callApi(url, "POST", contentType, params, null); + } + + /** + * Makes a synchronous POST request with specific contentType + * Will invalidate all caches with {@code tag} if not null + * @param url URL to post to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to post + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_POST(URL url, String contentType, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "POST", contentType, params, CACHE_TAG); + } + + + /** + * Makes a synchronous PUT request with {@link Http#urlEncodedContentType} contentType + * @param url URL to put to + * @param params Map, a generic Map containing data to put + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_PUT(URL url, Map params) throws HttpException { + return callApi(url, "PUT", PlainHttpService.urlEncodedContentType, params, null); + } + + /** + * Makes a synchronous PUT request with {@link Http#urlEncodedContentType} contentType + * Will invalidate all caches with {@code tag} if not null + * @param url URL to put to + * @param params Map, a generic Map containing data to put + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_PUT(URL url, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "PUT", PlainHttpService.urlEncodedContentType, params, CACHE_TAG); + } + + + /** + * Makes a synchronous PUT request with specific contentType + * @param url URL to put to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to put + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_PUT(URL url, String contentType, Map params) throws HttpException { + return callApi(url, "PUT", contentType, params, null); + } + + /** + * Makes a synchronous PUT request with specific contentType + * Will invalidate all caches with {@code tag} if not null + * @param url URL to put to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to put + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_PUT(URL url, String contentType, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "PUT", contentType, params, CACHE_TAG); + } + + + /** + * Makes a synchronous DELETE request + * @param url URL to delete to + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url) throws HttpException { + return callApi(url, "DELETE", PlainHttpService.urlEncodedContentType, null, null); + } + + /** + * Makes a synchronous DELETE request + * Will invalidate all caches with {@code tag} if not null + * @param url URL to delete to + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "DELETE", PlainHttpService.urlEncodedContentType, null, CACHE_TAG); + } + + + /** + * Makes a synchronous DELETE request with parameters and {@link Http#urlEncodedContentType} contentType + * @param url URL to delete to + * @param params Map, a generic Map containing data to put + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url, Map params) throws HttpException { + return callApi(url, "DELETE", PlainHttpService.urlEncodedContentType, params, null); + } + + /** + * Makes a synchronous DELETE request with parameters and {@link Http#urlEncodedContentType} contentType + * Will invalidate all caches with {@code tag} if not null + * @param url URL to delete to + * @param params Map, a generic Map containing data to put + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "DELETE", PlainHttpService.urlEncodedContentType, params, CACHE_TAG); + } + + + /** + * Makes a synchronous DELETE request with parameters and specific contentType + * @param url URL to delete to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to put + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url, String contentType, Map params) throws HttpException { + return callApi(url, "DELETE", contentType, params, null); + } + + /** + * Makes a synchronous DELETE request with parameters and specific contentType + * Will invalidate all caches with {@code tag} if not null + * @param url URL to delete to + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType}. + * @param params Map, a generic Map containing data to put + * @param CACHE_TAG the cache TAG to invalidate + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + public HttpServiceResponse api_DELETE(URL url, String contentType, Map params, @Nullable String CACHE_TAG) throws HttpException { + return callApi(url, "DELETE", contentType, params, CACHE_TAG); + } + + /** + * Subclasses must implement this + * @param url URL to call + * @param method String, can be GET, POST, PUT, DELETE, UPDATE + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType} + * @param params Map, a generic Map with parameters for POST, PUT or UPDATE. Will be serialized according + * to {@code contentType} + * @param CACHE_TAG the TAG for cache record, used only by GET + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + protected abstract HttpServiceResponse callApi(URL url, String method, String contentType, Map params, @Nullable String CACHE_TAG) throws HttpException; + +} diff --git a/src/main/bookingbugAPI2/services/http/OkHttpService.java b/src/main/bookingbugAPI2/services/http/OkHttpService.java new file mode 100644 index 0000000..2d670a8 --- /dev/null +++ b/src/main/bookingbugAPI2/services/http/OkHttpService.java @@ -0,0 +1,117 @@ +package bookingbugAPI2.services.http; + +import bookingbugAPI2.models.HttpException; +import bookingbugAPI2.services.ConfigService; +import bookingbugAPI2.services.logger.AbstractLoggerService; +import bookingbugAPI2.services.ServiceProvider; +import helpers2.Http; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import okhttp3.*; + +import java.io.IOException; +import java.net.URL; +import java.util.Map; +import java.util.Objects; + + +/** + * Created by sebi on 23.05.2016. + */ +public class OkHttpService extends AbstractHttpService { + + private final OkHttpClient client = new OkHttpClient(); + + public OkHttpService(ServiceProvider provider) { + super(provider); + } + + + /** + * Make a synchronous configurable network request. Uses headers and other config from {@link ServiceProvider#configService()} + * If the {@code method} is GET, then response caching will be enabled + * @param url URL to call + * @param method String, can be GET, POST, PUT, DELETE, UPDATE + * @param contentType String, can be {@link Http#urlEncodedContentType} or {@link Http#jsonContentType} + * @param params Map, a generic Map with parameters for POST, PUT or UPDATE. Will be serialized according + * to {@code contentType} + * @param CACHE_TAG the TAG for cache record + * @return {@link HttpServiceResponse} + * @throws HttpException + */ + protected HttpServiceResponse callApi(URL url, String method, String contentType, Map params, String CACHE_TAG) throws HttpException { + ConfigService config = provider.configService(); + AbstractLoggerService.Logger logger = provider.loggerService().getLogger(OkHttpService.class.getName()); + PlainHttpService.NetResponse cache = null; + + if(Objects.equals(method, "GET")) + cache = provider.cacheService().getDBResponse(url.toString(), method); + + if(cache != null) { + logger.v("Response for {0} {1} loaded from cache", method, url); + return new HttpServiceResponse(Utils.stringToContentRep(cache.getResp()), url.toString(), method, contentType, params, config.auth_token); + } + + //http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0 + System.setProperty("jsse.enableSNIExtension", "false"); + + Request.Builder builder = new Request.Builder() + .header("User-Agent", config.userAgent) + .header("App-Id", config.appId) + .header("App-Key", config.appKey) + .url(url.toString()); + + if(config.auth_token != null) + builder.header("Auth-Token", config.auth_token); + + String body = null; + if(params != null) { + try { + body = Http.getEncoder(contentType).encode(params); + } catch (Http.EncodingException | Http.UnknownContentType e) { + logger.e(e, "Unknown Error"); + throw new HttpException("Error", e) ; + } + } + + if(Objects.equals(method, "POST") && body != null) { + builder.post(RequestBody.create(MediaType.parse(contentType), body)); + } else if(Objects.equals(method, "PUT") && body != null) { + builder.put(RequestBody.create(MediaType.parse(contentType), body)); + } else if(Objects.equals(method, "DELETE") && body != null) { + builder.delete(RequestBody.create(MediaType.parse(contentType), body)); + } else if(Objects.equals(method, "DELETE")) { + builder.delete(); + } + + Request request = builder.build(); + + Response response; + try { + response = client.newCall(request).execute(); + if (!response.isSuccessful()) { + logger.e("Failed request: {0} {1} {2} {3}", response.code(), method, url, response.message()); + //String message = response.message() + response.body().string(); + String message = response.body().string(); + throw new HttpException("Unexpected code " + response, message, response.code()); + } + else logger.d("{0} {1} {2}", response.code(), method, url); + + String raw_resp = response.body().string(); + + if(Objects.equals(method, "GET")) + provider.cacheService().storeResult(url.toString(), method, raw_resp, CACHE_TAG); + else if(CACHE_TAG != null) { + //POST / PUT / UPDATE / DELETE methods => invalidate cache with provided tag + provider.cacheService().invalidateResultsByTag(CACHE_TAG); + } + + return new HttpServiceResponse(Utils.stringToContentRep(raw_resp), url.toString(), method, contentType, params, config.auth_token); + } catch (IOException e) { + logger.e(e, "Unknown Error"); + if(e instanceof HttpException) throw (HttpException)e; + throw new HttpException("Error", e) ; + } + + } +} diff --git a/src/main/bookingbugAPI/services/HttpService.java b/src/main/bookingbugAPI2/services/http/PlainHttpService.java similarity index 90% rename from src/main/bookingbugAPI/services/HttpService.java rename to src/main/bookingbugAPI2/services/http/PlainHttpService.java index 9b46474..b920a30 100644 --- a/src/main/bookingbugAPI/services/HttpService.java +++ b/src/main/bookingbugAPI2/services/http/PlainHttpService.java @@ -1,8 +1,6 @@ -package bookingbugAPI.services; +package bookingbugAPI2.services.http; -import bookingbugAPI.models.HttpException; -import bookingbugAPI.models.PublicRoot; -import com.fasterxml.jackson.core.JsonProcessingException; +import bookingbugAPI2.models.HttpException; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.dao.DaoManager; import com.j256.ormlite.field.DatabaseField; @@ -11,28 +9,26 @@ import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.DatabaseTable; import com.j256.ormlite.table.TableUtils; -import com.theoryinpractise.halbuilder.api.ContentRepresentation; import com.theoryinpractise.halbuilder.api.RepresentationFactory; -import helpers.Config; -import bookingbugAPI.models.BBRoot; -import helpers.Http; -import helpers.HttpServiceResponse; -import helpers.hal_addon.CustomJsonRepresentationFactory; +import helpers2.Config; +import helpers2.Http; +import helpers2.HttpServiceResponse; +import helpers2.hal_addon.CustomJsonRepresentationFactory; import java.io.*; -import java.lang.reflect.InvocationTargetException; import java.net.HttpURLConnection; import java.net.URL; import java.sql.SQLException; +import java.util.Date; import java.util.List; import java.util.Map; import java.util.logging.Logger; import static com.theoryinpractise.halbuilder.api.RepresentationFactory.HAL_JSON; -public class HttpService { +public class PlainHttpService { - private final static Logger log = Logger.getLogger(HttpService.class.getName()); + private final static Logger log = Logger.getLogger(PlainHttpService.class.getName()); public final static String jsonContentType = "application/json"; public final static String urlEncodedContentType = "application/x-www-form-urlencoded"; @@ -120,7 +116,7 @@ private static HttpServiceResponse callApi(URL url, String auth_token, String me CustomJsonRepresentationFactory representationFactory = new CustomJsonRepresentationFactory(); representationFactory.withFlag(RepresentationFactory.STRIP_NULLS); Reader reader = new InputStreamReader(new ByteArrayInputStream(cache.resp.getBytes())); - return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), method, contentType, params, auth_token); + return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), url.toString(), method, contentType, params, auth_token); } //http://stackoverflow.com/questions/7615645/ssl-handshake-alert-unrecognized-name-error-since-upgrade-to-java-1-7-0 @@ -181,11 +177,11 @@ private static HttpServiceResponse callApi(URL url, String auth_token, String me //System.out.println("Error message: "+ errorMessage); } else { Reader reader = new InputStreamReader(new ByteArrayInputStream(returnString.getBytes())); - return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), method, contentType, params, auth_token); + return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), url.toString(), method, contentType, params, auth_token); } } else { Reader reader = new InputStreamReader(new ByteArrayInputStream(returnString.getBytes())); - return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), method, contentType, params, auth_token); + return new HttpServiceResponse(representationFactory.readRepresentation(HAL_JSON, reader), url.toString(), method, contentType, params, auth_token); } } catch (IOException e) { @@ -269,16 +265,34 @@ public static class NetResponse { @DatabaseField private String resp; + @DatabaseField(version = true) + private Date timestamp; + + @DatabaseField + private String CACHE_TAG; + public NetResponse(){} public NetResponse(String url, String method, String resp) { this.url = url; this.method = method; this.resp = resp; + this.CACHE_TAG = null; + } + + public NetResponse(String url, String method, String resp, String CACHE_TAG) { + this.url = url; + this.method = method; + this.resp = resp; + this.CACHE_TAG = CACHE_TAG; } public String getResp() { return resp; } + + public Date getTimestamp() { + return timestamp; + } } } \ No newline at end of file diff --git a/src/main/bookingbugAPI2/services/logger/AbstractLoggerService.java b/src/main/bookingbugAPI2/services/logger/AbstractLoggerService.java new file mode 100644 index 0000000..fbfa1d4 --- /dev/null +++ b/src/main/bookingbugAPI2/services/logger/AbstractLoggerService.java @@ -0,0 +1,95 @@ +package bookingbugAPI2.services.logger; + +/** + * Created by sebi on 05.07.2016. + */ +public abstract class AbstractLoggerService { + + public abstract Logger getLogger(String TAG); + + public interface Logger { + /** + * Log a verbose message + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void v(String message, Object... args); + + /** + * Log a verbose exception and a message + * @param t the throwable + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void v(Throwable t, String message, Object... args); + + /** + * Log a debug message + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void d(String message, Object... args); + + /** + * Log a debug exception and a message + * @param t the throwable + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void d(Throwable t, String message, Object... args); + + /** + * Log an info message + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void i(String message, Object... args); + + /** + * Log an info exception and a message + * @param t the throwable + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void i(Throwable t, String message, Object... args); + + /** + * Log a warning message + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void w(String message, Object... args); + + /** + * Log a warning exception and a message + * @param t the throwable + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void w(Throwable t, String message, Object... args); + + /** + * Log an error message + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void e(String message, Object... args); + + /** + * Log an error exception and a message + * @param t the throwable + * @param message the message to log. Can contain formatting like {0} {1} which are replaced by {@code args} + * @param args Additional objects to print inside the message + */ + void e(Throwable t, String message, Object... args); + } + + public static abstract class AbstractLogger implements Logger { + protected final String TAG; + + public AbstractLogger(String TAG) { + this.TAG = TAG; + } + } + +} diff --git a/src/main/bookingbugAPI2/services/logger/JavaLoggerService.java b/src/main/bookingbugAPI2/services/logger/JavaLoggerService.java new file mode 100644 index 0000000..1a78aad --- /dev/null +++ b/src/main/bookingbugAPI2/services/logger/JavaLoggerService.java @@ -0,0 +1,213 @@ +package bookingbugAPI2.services.logger; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Date; +import java.util.HashMap; +import java.util.logging.*; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Created by sebi on 06.07.2016. + */ +public class JavaLoggerService extends AbstractLoggerService { + + HashMap loggers = new HashMap<>(); + + @Override + public Logger getLogger(String TAG) { + //Get cached logger + if(loggers.containsKey(TAG)) + return loggers.get(TAG); + + Logger logger = new JavaLogger(TAG); + loggers.put(TAG, logger); + return logger; + } + + public static class JavaLogger extends AbstractLogger implements AbstractLoggerService.Logger { + + //Custom log levels (INFO is higher than DEBUG) + public static final Level DEBUG = new Level("DEBUG", Level.INFO.intValue() + 1){}; + public static final Level INFO = new Level("INFO", Level.INFO.intValue() + 2){}; + + //Custom Formatter to display correct Class and Method name + public static final Formatter formatter = new Formatter() { + private final String format = "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s%n%4$s: %5$s%6$s%n"; + private final Date dat = new Date(); + + @Override + public String format(LogRecord record) { + dat.setTime(record.getMillis()); + String source; + + inferCaller(record); + + if (record.getSourceClassName() != null) { + source = record.getSourceClassName(); + if (record.getSourceMethodName() != null) { + source += " " + record.getSourceMethodName(); + } + } else { + source = record.getLoggerName(); + } + String message = formatMessage(record); + String throwable = ""; + if (record.getThrown() != null) { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + pw.println(); + record.getThrown().printStackTrace(pw); + pw.close(); + throwable = sw.toString(); + } + return String.format(format, + dat, + source, + record.getLoggerName(), + record.getLevel(), + message, + throwable); + } + + // Private method to infer the caller's class and method names + // The isLoggerImplFrame is different and uses StackTrace + private void inferCaller(LogRecord record) { + Throwable throwable = new Throwable(); + StackTraceElement[] stackTrace = throwable.getStackTrace(); + + int depth = stackTrace.length; + boolean lookingForLogger = true; + for (int ix = 0; ix < depth; ix++) { + StackTraceElement frame = stackTrace[ix]; + String cname = frame.getClassName(); + boolean isLoggerImpl = isLoggerImplFrame(cname); + // Skip all frames until we have found the last logger frame. + if (!isLoggerImpl) { + // skip reflection call + if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) { + // We've found the relevant frame. + record.setSourceClassName(cname); + record.setSourceMethodName(frame.getMethodName()); + return; + } + } + } + } + + /** + * Overridden from SimpleFormatter to provide the correct logger class + * @param cname The class name + * @return + */ + private boolean isLoggerImplFrame(String cname) { + // the log record could be created for a platform logger + return (cname.equals("java.util.logging.logger") || + cname.startsWith("java.util.logging.LoggingProxyImpl") || + cname.startsWith("sun.util.logging.") || + cname.startsWith("java.util.logging.") || + cname.startsWith(JavaLogger.class.getName())); + } + }; + + + final java.util.logging.Logger logger; + + public JavaLogger(String TAG) { + super(TAG); + logger = java.util.logging.Logger.getLogger(TAG); + + //ConsoleHandler with custom formatter + ConsoleHandler consoleHandler = new ConsoleHandler(); + consoleHandler.setFormatter(formatter); + consoleHandler.setLevel(Level.FINER); + + logger.setUseParentHandlers(false); + Handler[] handlers = logger.getHandlers(); + for(Handler handler : handlers) + if(handler.getClass() == ConsoleHandler.class) + logger.removeHandler(handler); + + logger.addHandler(consoleHandler); + logger.setLevel(Level.FINER); + } + + @Override + public void v(String message, Object... args) { + log(Level.FINER, null, message, args); + } + + @Override + public void v(Throwable t, String message, Object... args) { + log(Level.FINER, t, message, args); + } + + @Override + public void d(String message, Object... args) { + log(DEBUG, null, message, args); + } + + @Override + public void d(Throwable t, String message, Object... args) { + log(DEBUG, t, message, args); + } + + @Override + public void i(String message, Object... args) { + log(INFO, null, message, args); + } + + @Override + public void i(Throwable t, String message, Object... args) { + log(INFO, t, message, args); + } + + @Override + public void w(String message, Object... args) { + log(Level.WARNING, null, message, args); + } + + @Override + public void w(Throwable t, String message, Object... args) { + log(Level.WARNING, t, message, args); + } + + @Override + public void e(String message, Object... args) { + log(Level.SEVERE, null, message, args); + } + + @Override + public void e(Throwable t, String message, Object... args) { + log(Level.SEVERE, t, message, args); + } + + private void log(java.util.logging.Level level, Throwable t, String message, Object... args) { + if(message == null || message.length() == 0) { + if(t != null) + message = t.toString(); + else return; //Swallow error + } else if(t != null) + message += "\n" + t.toString(); + + if(args.length > 0) { + //Format the message + StringBuffer stringBuffer = new StringBuffer(); + Matcher matcher = Pattern.compile("\\{\\d\\}").matcher(message); + + while (matcher.find()) { + String value = matcher.group(); + value = value.substring(1, value.length() - 1); + int pos = Integer.parseInt(value); + if(pos < args.length && args[pos] != null) + matcher.appendReplacement(stringBuffer, args[pos].toString()); + } + matcher.appendTail(stringBuffer); + message = stringBuffer.toString(); + } + + logger.log(level, message); + } + } +} diff --git a/src/main/helpers/Config.java b/src/main/helpers2/Config.java similarity index 99% rename from src/main/helpers/Config.java rename to src/main/helpers2/Config.java index e3f8d0b..2147604 100644 --- a/src/main/helpers/Config.java +++ b/src/main/helpers2/Config.java @@ -1,4 +1,4 @@ -package helpers; +package helpers2; import java.io.FileNotFoundException; import java.io.InputStream; diff --git a/src/main/helpers/Http.java b/src/main/helpers2/Http.java similarity index 99% rename from src/main/helpers/Http.java rename to src/main/helpers2/Http.java index 9607b70..28088f3 100644 --- a/src/main/helpers/Http.java +++ b/src/main/helpers2/Http.java @@ -1,4 +1,4 @@ -package helpers; +package helpers2; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/src/main/helpers/HttpServiceResponse.java b/src/main/helpers2/HttpServiceResponse.java similarity index 69% rename from src/main/helpers/HttpServiceResponse.java rename to src/main/helpers2/HttpServiceResponse.java index 8626f12..ecf9558 100644 --- a/src/main/helpers/HttpServiceResponse.java +++ b/src/main/helpers2/HttpServiceResponse.java @@ -1,6 +1,8 @@ -package helpers; +package helpers2; -import bookingbugAPI.services.HttpService; +import bookingbugAPI2.services.http.PlainHttpService; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; import com.theoryinpractise.halbuilder.api.ContentRepresentation; import java.util.Map; @@ -8,13 +10,16 @@ public class HttpServiceResponse { + @JsonIgnore protected ContentRepresentation rep; + protected String url; protected String method; - protected String contentType = HttpService.jsonContentType; + protected String contentType = PlainHttpService.jsonContentType; protected Map params; protected String authToken; + public HttpServiceResponse(){} public HttpServiceResponse(ContentRepresentation rep) { this.rep = rep; @@ -32,8 +37,9 @@ public HttpServiceResponse(ContentRepresentation rep, String method, Map params) } - public HttpServiceResponse(ContentRepresentation rep, String method, String contentType, Map params, String auth_token) { + public HttpServiceResponse(ContentRepresentation rep, String url, String method, String contentType, Map params, String auth_token) { this.rep = rep; + this.url = url; this.method = method; this.contentType = contentType; this.params = params; @@ -50,6 +56,23 @@ public void setRep(ContentRepresentation rep) { this.rep = rep; } + @JsonProperty + public String getRepString() { + return this.getRep().getContent(); + } + + public void setRepString(String rep) { + this.rep = Utils.stringToContentRep(rep); + } + + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } public String getMethod() { return method; @@ -60,6 +83,13 @@ public void setMethod(String method) { this.method = method; } + public String getAuthToken() { + return authToken; + } + + public void setAuthToken(String authToken) { + this.authToken = authToken; + } public void setParams(Map params) { this.params = params; @@ -70,6 +100,7 @@ public Map getParams() { return params; } + @JsonIgnore public String getParamsStr() { Config config = new Config(); diff --git a/src/main/helpers/TokenGenerator.java b/src/main/helpers2/TokenGenerator.java similarity index 86% rename from src/main/helpers/TokenGenerator.java rename to src/main/helpers2/TokenGenerator.java index d2df5f1..4a8c8fd 100644 --- a/src/main/helpers/TokenGenerator.java +++ b/src/main/helpers2/TokenGenerator.java @@ -1,4 +1,4 @@ -package helpers; +package helpers2; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -108,20 +108,21 @@ public String create(JsonNode json) throws Exception { } -/* public static void main(String[] args) { try { - JsonNode jsonObj = new JsonNode(); - jsonObj.put("first_name", "John"); - jsonObj.put("last_name", "Smith"); - jsonObj.put("email", "smith@example.com"); - jsonObj.put("mobile", "0123456789"); + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.createObjectNode(); - System.out.println(TokenGenerator.getInstance().create(jsonObj)); + //((ObjectNode)jsonNode).put("first_name", "John2"); + //((ObjectNode)jsonNode).put("last_name", "Smith"); + //((ObjectNode)jsonNode).put("email", "qais.mazhar@uk.pwc.com"); + //((ObjectNode)jsonNode).put("mobile", "0123466789"); + ((ObjectNode)jsonNode).put("reference", "512541251"); + + System.out.println(TokenGenerator.getInstance("37000", "zTV67mmwFYqZxM9wwqhjsOngs").create(jsonNode)); } catch (Exception e) { e.printStackTrace(); } } -*/ } \ No newline at end of file diff --git a/src/main/helpers/Utils.java b/src/main/helpers2/Utils.java similarity index 95% rename from src/main/helpers/Utils.java rename to src/main/helpers2/Utils.java index 3f5e75b..2eda191 100644 --- a/src/main/helpers/Utils.java +++ b/src/main/helpers2/Utils.java @@ -1,6 +1,6 @@ -package helpers; +package helpers2; -import bookingbugAPI.models.params.Params; +import bookingbugAPI2.models.params.Params; import com.damnhandy.uri.template.UriTemplate; import com.damnhandy.uri.template.UriTemplateBuilder; import com.fasterxml.jackson.databind.node.ArrayNode; @@ -9,17 +9,13 @@ import com.theoryinpractise.halbuilder.api.ContentRepresentation; import com.theoryinpractise.halbuilder.api.Link; import com.theoryinpractise.halbuilder.api.RepresentationFactory; -import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory; -import helpers.hal_addon.CustomJsonRepresentationFactory; +import helpers2.hal_addon.CustomJsonRepresentationFactory; -import javax.servlet.http.HttpSession; import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.HashMap; import java.util.Map; -import java.util.Set; import static com.theoryinpractise.halbuilder.api.RepresentationFactory.HAL_JSON; diff --git a/src/main/helpers/hal_addon/CustomJsonDeserializer.java b/src/main/helpers2/hal_addon/CustomJsonDeserializer.java similarity index 88% rename from src/main/helpers/hal_addon/CustomJsonDeserializer.java rename to src/main/helpers2/hal_addon/CustomJsonDeserializer.java index 348f58a..07528bc 100644 --- a/src/main/helpers/hal_addon/CustomJsonDeserializer.java +++ b/src/main/helpers2/hal_addon/CustomJsonDeserializer.java @@ -1,18 +1,14 @@ -package helpers.hal_addon; +package helpers2.hal_addon; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer; import com.fasterxml.jackson.databind.jsontype.TypeDeserializer; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.IOException; -import java.util.HashMap; /** * Created by sebi on 04.02.2016. diff --git a/src/main/helpers/hal_addon/CustomJsonRepresentationFactory.java b/src/main/helpers2/hal_addon/CustomJsonRepresentationFactory.java similarity index 83% rename from src/main/helpers/hal_addon/CustomJsonRepresentationFactory.java rename to src/main/helpers2/hal_addon/CustomJsonRepresentationFactory.java index 8ce48eb..9c6cfa8 100644 --- a/src/main/helpers/hal_addon/CustomJsonRepresentationFactory.java +++ b/src/main/helpers2/hal_addon/CustomJsonRepresentationFactory.java @@ -1,7 +1,6 @@ -package helpers.hal_addon; +package helpers2.hal_addon; import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory; -import com.theoryinpractise.halbuilder.json.JsonRepresentationReader; import com.theoryinpractise.halbuilder.json.JsonRepresentationWriter; /** diff --git a/src/main/helpers/hal_addon/CustomJsonRepresentationReader.java b/src/main/helpers2/hal_addon/CustomJsonRepresentationReader.java similarity index 97% rename from src/main/helpers/hal_addon/CustomJsonRepresentationReader.java rename to src/main/helpers2/hal_addon/CustomJsonRepresentationReader.java index 3d5e693..c4bceba 100644 --- a/src/main/helpers/hal_addon/CustomJsonRepresentationReader.java +++ b/src/main/helpers2/hal_addon/CustomJsonRepresentationReader.java @@ -1,8 +1,7 @@ -package helpers.hal_addon; +package helpers2.hal_addon; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.module.SimpleModule; import com.google.common.collect.ImmutableMap; import com.google.common.io.CharStreams; import com.theoryinpractise.halbuilder.AbstractRepresentationFactory; @@ -12,7 +11,6 @@ import com.theoryinpractise.halbuilder.impl.api.Support; import com.theoryinpractise.halbuilder.impl.representations.ContentBasedRepresentation; import com.theoryinpractise.halbuilder.impl.representations.MutableRepresentation; -import com.theoryinpractise.halbuilder.json.JsonRepresentationReader; import java.io.IOException; import java.io.Reader; diff --git a/src/test/bookingbugAPI/api/admin/AbstractAPITest.java b/src/test/bookingbugAPI/api/admin/AbstractAPITest.java deleted file mode 100644 index 3fd8908..0000000 --- a/src/test/bookingbugAPI/api/admin/AbstractAPITest.java +++ /dev/null @@ -1,47 +0,0 @@ -package bookingbugAPI.api.admin; - -import bookingbugAPI.api.API; -import bookingbugAPI.models.Company; -import bookingbugAPI.services.CacheService; -import org.junit.After; -import org.junit.Before; - -import static org.junit.Assert.assertNotNull; - -/** - * Created by sebi on 10.06.2016. - */ -public abstract class AbstractAPITest { - - protected static final String companyId = "37025"; - protected static final String token = "x2_5PcI15mq7sEWm70JazA"; - - protected API defaultAPI; - - @Before - public void setUp() { - defaultAPI = new API.APIBuilder() - .withCache(CacheService.MOCK()) - .withAuthToken(token) - .build(); - }; - - @After - public void tearDown() { - defaultAPI = null; - }; - - public Company getCompany() { - Company company = null; - API.APIBuilder builder = new API.APIBuilder().withCache(CacheService.JDBC()).withAuthToken(token); - API api = builder.build(); - - try { - company = api.admin().company().companyRead(companyId); - }catch (Exception e) { - e.printStackTrace(); - } - assertNotNull(company); - return company; - } -} diff --git a/src/test/bookingbugAPI/api/admin/BookingAPITest.java b/src/test/bookingbugAPI/api/admin/BookingAPITest.java deleted file mode 100644 index 85d2e91..0000000 --- a/src/test/bookingbugAPI/api/admin/BookingAPITest.java +++ /dev/null @@ -1,66 +0,0 @@ -package bookingbugAPI.api.admin; - -import bookingbugAPI.models.BBCollection; -import bookingbugAPI.models.Booking; -import bookingbugAPI.models.Company; -import bookingbugAPI.models.SchemaForm; -import bookingbugAPI.models.params.BookingListParams; -import org.junit.Before; -import org.junit.Test; - -import java.io.IOException; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -/** - * Created by sebi on 18.05.2016. - */ -public class BookingAPITest extends AbstractAPITest{ - - private Company company; - - @Override - @Before - public void setUp() { - super.setUp(); - company = getCompany(); - } - - @Test - public void bookingList(){ - try { - BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingListParams(1).setPerPage(10)); - assertNotNull(bookings); - assertTrue(bookings.size() > 0); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void bookingRead(){ - try { - BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingListParams(1).setPerPage(10)); - Booking booking = defaultAPI.admin().booking().bookingRead(company, bookings.getObjectAtIndex(0).id); - assertNotNull(booking); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void bookingEditSchema() { - try { - //Paginated services - BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingListParams(1).setPerPage(10)); - SchemaForm schemaForm = defaultAPI.admin().booking().getEditBookingSchema(bookings.getObjectAtIndex(0)); - assertNotNull(schemaForm); - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - } - } -} diff --git a/src/test/bookingbugAPI/api/admin/CompanyAPITest.java b/src/test/bookingbugAPI/api/admin/CompanyAPITest.java deleted file mode 100644 index 5b2adec..0000000 --- a/src/test/bookingbugAPI/api/admin/CompanyAPITest.java +++ /dev/null @@ -1,47 +0,0 @@ -package bookingbugAPI.api.admin; - -import bookingbugAPI.api.API; -import bookingbugAPI.api.AdminURLS; -import bookingbugAPI.models.Company; -import bookingbugAPI.models.Currency; -import bookingbugAPI.models.SchemaForm; -import bookingbugAPI.services.CacheService; -import bookingbugAPI.services.HttpService; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.net.URL; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Created by sebi on 09.06.2016. - */ -public class CompanyAPITest extends AbstractAPITest{ - - private Company company; - - @Override - @Before - public void setUp() { - super.setUp(); - company = getCompany(); - } - - @Test - public void companyRead() { - assertNotNull(company); - } - - @Test - public void companySettings(){ - try { - assertNotNull(company.getSettings()); - assertEquals(company.getSettings().getCurrency(), Currency.GBP); - }catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/test/bookingbugAPI/api/admin/ServiceAPITest.java b/src/test/bookingbugAPI/api/admin/ServiceAPITest.java deleted file mode 100644 index 66a3ea6..0000000 --- a/src/test/bookingbugAPI/api/admin/ServiceAPITest.java +++ /dev/null @@ -1,101 +0,0 @@ -package bookingbugAPI.api.admin; - -import bookingbugAPI.models.BBCollection; -import bookingbugAPI.models.Company; -import bookingbugAPI.models.SchemaForm; -import bookingbugAPI.models.Service; -import bookingbugAPI.models.params.ServiceListParams; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -/** - * Created by sebi on 10.06.2016. - */ -public class ServiceAPITest extends AbstractAPITest { - - private Company company; - - @Override - @Before - public void setUp() { - super.setUp(); - company = getCompany(); - } - - @Test - public void serviceList() { - try { - BBCollection services; - - //All services - services = defaultAPI.admin().service().serviceList(company, null); - assertNotNull(services); - - //Paginated services - services = defaultAPI.admin().service().serviceList(company, new ServiceListParams().setPage(1).setPerPage(5)); - assertNotNull(services); - assertEquals(services.size(), 5); - - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - } - } - - @Test - public void serviceRead() { - try { - //All services - BBCollection services = defaultAPI.admin().service().serviceList(company, null); - Service service = defaultAPI.admin().service().serviceRead(company, services.getObjectAtIndex(0).id); - assertNotNull(service); - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - - - } - } - - @Test - public void serviceNewSchema() { - try { - //Paginated services - SchemaForm schemaForm = defaultAPI.admin().service().getNewServiceSchema(company); - assertNotNull(schemaForm); - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - } - } - - @Test - public void serviceEditSchema() { - try { - //Paginated services - BBCollection services = defaultAPI.admin().service().serviceList(company, null); - SchemaForm schemaForm = defaultAPI.admin().service().getEditServiceSchema(services.getObjectAtIndex(0)); - assertNotNull(schemaForm); - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - } - } - - @Test - public void serviceNewBookingSchema() { - try { - //Paginated services - BBCollection services = defaultAPI.admin().service().serviceList(company, null); - SchemaForm schemaForm = defaultAPI.admin().service().getNewBookingSchema(services.getObjectAtIndex(0)); - assertNotNull(schemaForm); - }catch (Exception e) { - e.printStackTrace(); - assert false : e; - } - } - -} diff --git a/src/test/bookingbugAPI/api/PublicURLSTest.java b/src/test/bookingbugAPI2/api/PublicURLSTest.java similarity index 98% rename from src/test/bookingbugAPI/api/PublicURLSTest.java rename to src/test/bookingbugAPI2/api/PublicURLSTest.java index 5600746..d0eee5f 100644 --- a/src/test/bookingbugAPI/api/PublicURLSTest.java +++ b/src/test/bookingbugAPI2/api/PublicURLSTest.java @@ -1,4 +1,4 @@ -package bookingbugAPI.api; +package bookingbugAPI2.api; import org.junit.*; import static org.junit.Assert.*; diff --git a/src/test/bookingbugAPI2/api/admin/AbstractAPITest.java b/src/test/bookingbugAPI2/api/admin/AbstractAPITest.java new file mode 100644 index 0000000..b36ebc4 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/AbstractAPITest.java @@ -0,0 +1,188 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.api.API; +import bookingbugAPI2.api.AbstractAPI; +import bookingbugAPI2.models.*; +import bookingbugAPI2.services.cache.MockCacheService; +import bookingbugAPI2.services.cache.SQLiteCacheService; +import bookingbugAPI2.services.http.OkHttpService; +import bookingbugAPI2.services.ServiceProvider; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import helpers2.HttpServiceResponse; +import org.junit.After; +import org.junit.Before; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Map; + +import static org.junit.Assert.assertNotNull; + +/** + * Created by sebi on 10.06.2016. + */ +public abstract class AbstractAPITest { + + protected static final String companyId = "36990"; + protected static final String resourceId = "5"; + protected static final String adminId = "23455"; + protected static final String personId = "15289"; + protected static final String clinicId = "12345"; + + protected static final String token = "ro13e9jaWi3kvA4fMToU1w"; + + protected API defaultAPI; + protected API mockAPI; + + /** + * Class used to mock all http calls to a predefined server. The root path of original URL is replaced with a predefined one + * (For calls which have the url from model links) + */ + private class MockHttpService extends OkHttpService { + + public MockHttpService(ServiceProvider provider) { + super(provider); + } + + @Override + protected HttpServiceResponse callApi(URL url, String method, String contentType, Map params, String CACHE_TAG) throws HttpException { + String strUrl = url.toString(); + strUrl = strUrl.replaceFirst("^(?:https?:\\/\\/)?(?:[^@\\n]+@)?(?:www\\.)?([^:\\/\\n]+)(:\\d+)?", provider.configService().serverUrl); + try { + return super.callApi(new URL(strUrl), method, contentType, params, CACHE_TAG); + } catch (MalformedURLException e) { + e.printStackTrace(); + throw new HttpException("Cannot replace url with mock", e); + } + } + } + + @Before + public void setUp() { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig() + .withCacheService(new MockCacheService()) + .withAuthToken(token); + defaultAPI = new API(config); + } + + @After + public void tearDown() { + defaultAPI = null; + } + + /** + * Starts a {@link MockWebServer} and initializes an api with the server's url + * The api uses a custom HttpService {@link MockHttpService} which replaces all + * @param dispatcher The dispatcher to mock http calls + * @return the server + * @throws IOException + */ + public MockWebServer mockServer(Dispatcher dispatcher) throws IOException { + MockWebServer server = new MockWebServer(); + server.setDispatcher(dispatcher); + server.start(); + + //Server url must not end in '/' + String serverUrl = server.url("").toString(); + if(serverUrl.endsWith("/")) + serverUrl = serverUrl.substring(0, serverUrl.length()-1); + + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig() + .withCacheService(new MockCacheService()) + .withAuthToken(token) + .withServerUrl(serverUrl); + config.withHttpService(new MockHttpService(config)); + mockAPI = new API(config); + + return server; + } + + public Company getCompany() { + Company company = null; + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(token); + config.withCacheService(new SQLiteCacheService(config)); + API api = new API(config); + return getCompany(api); + } + + public Company getCompany(API api) { + Company company = null; + try { + company = api.admin().company().companyRead(companyId); + }catch (Exception e) { + e.printStackTrace(); + } + assertNotNull(company); + return company; + } + + public Resource getResource() { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(token); + config.withCacheService(new SQLiteCacheService(config)); + return getResource(new API(config)); + } + + public Resource getResource(API api) { + Resource resource = null; + try { + resource = api.admin().resource().resourceRead(getCompany(), resourceId); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(resource); + return resource; + } + + public Administrator getAdministrator() { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(token); + config.withCacheService(new SQLiteCacheService(config)); + return getAdministrator(new API(config)); + } + + public Administrator getAdministrator(API api) { + Administrator administrator = null; + try { + administrator = api.admin().administrator().administratorRead(getCompany(), adminId); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(administrator); + return administrator; + } + + public Person getPerson() { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(token); + config.withCacheService(new SQLiteCacheService(config)); + return getPerson(new API(config)); + } + + public Person getPerson(API api) { + Person person = null; + try { + person = api.admin().person().personRead(getCompany(), personId); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(person); + return person; + } + + public Clinic getClinic() { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(token); + config.withCacheService(new SQLiteCacheService(config)); + return getClinic(new API(config)); + } + + public Clinic getClinic(API api) { + Clinic clinic = null; + try { + clinic = api.admin().clinic().clinicRead(getCompany(), clinicId); + } catch (IOException e) { + e.printStackTrace(); + } + assertNotNull(clinic); + return clinic; + } +} diff --git a/src/test/bookingbugAPI2/api/admin/AddressAPITest.java b/src/test/bookingbugAPI2/api/admin/AddressAPITest.java new file mode 100644 index 0000000..053af9c --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/AddressAPITest.java @@ -0,0 +1,144 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.AddressParams; +import bookingbugAPI2.models.params.Params; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class AddressAPITest extends AbstractAPITest { + + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/address.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void addressList() { + try { + BBCollection
addresses; + + //All addresses + addresses = defaultAPI.admin().address().addressList(company, new Params()); + assertNotNull(addresses); + + //Paginated addresses + addresses = defaultAPI.admin().address().addressList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(addresses); + assertTrue(addresses.size() <= 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void addressRead() { + try { + BBCollection
addresses = defaultAPI.admin().address().addressList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(addresses); + assertTrue(addresses.size() <= 5); + + //Read the first address by id + Address address = defaultAPI.admin().address().addressRead(company, addresses.getObjectAtIndex(0).id); + assertNotNull(address); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + // TODO: Fix Method not allowed + @Ignore + @Test + public void addressUpdate() { + try { + BBCollection
addresses = defaultAPI.admin().address().addressList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(addresses); + + AddressParams.Update params = new AddressParams.Update() + .setAddress1("Test1") + .setPostcode("12345"); + + Address address = defaultAPI.admin().address().addressUpdate(company, params); + assertNotNull(address); + assertEquals(address.getAddress1(), params.getAddress1()); + assertEquals(address.getPostcode(), params.getPostcode()); + + //TODO: expand here asserts + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void addressCreate() { + try { + MockWebServer server = mockServer(dispatcher); + AddressParams.Create params = new AddressParams.Create() + .setAddress1("Address1") + .setAddress2("Address2"); + + Address address = mockAPI.admin().address().addressCreate(getCompany(), params); + assertNotNull(address); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void addressDelete() { + try { + MockWebServer server = mockServer(dispatcher); + + BBCollection
addresses = defaultAPI.admin().address().addressList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(addresses); + + // TODO: 13.07.2016 test delete address + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/AdministratorAPITest.java b/src/test/bookingbugAPI2/api/admin/AdministratorAPITest.java new file mode 100644 index 0000000..5a9c283 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/AdministratorAPITest.java @@ -0,0 +1,193 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.AdministratorParams; +import bookingbugAPI2.models.params.Params; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +//TODO: Fix administrator missing info (use a predefined company and admin list +@Ignore +public class AdministratorAPITest extends AbstractAPITest { + + private Administrator administrator; + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/admin.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(200).setBody(ModelTest.getJSON("json/admin.json").toString()); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + MockWebServer server = null; + try { + server = mockServer(dispatcher); + administrator = getAdministrator(mockAPI); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + administrator = null; + } + } + + @Test + public void administratorList() { + try { + BBCollection administrators; + + //All administrators + administrators = defaultAPI.admin().administrator().administratorList(company, null); + assertNotNull(administrators); + + //Paginated administrators + administrators = defaultAPI.admin().administrator().administratorList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(administrators); + assertEquals(administrators.size(), 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void administratorRead() { + try { + BBCollection administrators = defaultAPI.admin().administrator().administratorList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(administrators); + assertEquals(administrators.size(), 5); + + //Read the first administrator by id + Administrator administrator = defaultAPI.admin().administrator().administratorRead(company, administrators.getObjectAtIndex(0).id); + assertNotNull(administrator); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void getAdministratorForLogin() throws IOException { + MockWebServer server = mockServer(dispatcher); + //TODO: replace with login api + Login login = new Login(new HttpServiceResponse(Utils.stringToContentRep(ModelTest.getJSON("json/login.json").toString()))); + + Administrator administrator = mockAPI.admin().administrator().getAdministratorForLogin(login); + assertNotNull(administrator); + + server.shutdown(); + } + + //TODO: Fix 405 Not allowed + @Ignore + @Test + public void administratorUpdate() { + try { + BBCollection administrators = defaultAPI.admin().administrator().administratorList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(administrators); + + AdministratorParams.Update params = new AdministratorParams.Update() + .setName("Test") + .setPersonId(12345); + + Administrator administrator = defaultAPI.admin().administrator().administratorUpdate(company, administrators.getObjectAtIndex(0).id, params); + assertNotNull(administrator); + assertEquals(administrator.getName(), params.getName()); + assertEquals(administrator.getPersonId(), params.getPersonId()); + + //TODO: expand here asserts + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void administratorCreate() { + try { + MockWebServer server = mockServer(dispatcher); + AdministratorParams.Create params = new AdministratorParams.Create() + .setPersonId(16246) + .setRole("user"); + + Administrator administrator = mockAPI.admin().administrator().administratorCreate(getCompany(), params); + assertNotNull(administrator); + assertEquals(administrator.getRole(), params.getRole()); + assertEquals(administrator.getPersonId(), params.getPersonId()); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void administratorDelete() { + try { + MockWebServer server = mockServer(dispatcher); + + BBCollection administrators = defaultAPI.admin().administrator().administratorList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(administrators); + + // TODO: Test delete administrator + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void administratorNewSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().administrator().getNewAdministratorSchema(company); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: schema is null + @Ignore + @Test + public void administratorEditSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().administrator().getEditAdministratorSchema(administrator); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/BookingAPITest.java b/src/test/bookingbugAPI2/api/admin/BookingAPITest.java new file mode 100644 index 0000000..2308318 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/BookingAPITest.java @@ -0,0 +1,141 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.BookingListParams; +import bookingbugAPI2.models.params.BookingParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Created by sebi on 18.05.2016. + */ +public class BookingAPITest extends AbstractAPITest{ + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if( (Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT") || Objects.equals(request.getMethod(), "DELETE")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/booking.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void bookingList(){ + try { + BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingParams.List(1, 10)); + assertNotNull(bookings); + assertTrue(bookings.size() > 0); + + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void bookingRead(){ + try { + BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingParams.List(1, 10)); + Booking booking = defaultAPI.admin().booking().bookingRead(company, bookings.getObjectAtIndex(0).id); + assertNotNull(booking); + } catch (IOException e) { + e.printStackTrace(); + } + } + + @Test + public void bookingEditSchema() { + try { + //Paginated services + BBCollection bookings = defaultAPI.admin().booking().bookingList(company, new BookingParams.List(1, 10)); + SchemaForm schemaForm = defaultAPI.admin().booking().getEditBookingSchema(bookings.getObjectAtIndex(0)); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void bookingCreate() { + try { + MockWebServer server = mockServer(dispatcher); + BookingParams.Create params = new BookingParams.Create() + .setDatetime(new DateTime()) + .setNotifications(true); + Booking booking = mockAPI.admin().booking().bookingCreate(company, params); + + assertNotNull(booking); + server.shutdown(); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void bookingUpdate() { + try { + Booking toUpdate = new Booking(new HttpServiceResponse(Utils.stringToContentRep(ModelTest.getJSON("json/booking.json").toString()))); + MockWebServer server = mockServer(dispatcher); + BookingParams.Update params = new BookingParams.Update() + .setDatetime(new DateTime()); + Booking booking = mockAPI.admin().booking().bookingUpdate(toUpdate, params); + + assertNotNull(booking); + server.shutdown(); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void bookingCancel() { + try { + MockWebServer server = mockServer(dispatcher); + BookingParams.Cancel params = new BookingParams.Cancel() + .setNotify(true) + .setCancelReason("Because"); + Booking booking = new Booking(new HttpServiceResponse(Utils.stringToContentRep(ModelTest.getJSON("json/booking.json").toString()))); + booking = mockAPI.admin().booking().cancelBooking(booking, params); + assertNotNull(booking); + + server.shutdown(); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/ClientAPITest.java b/src/test/bookingbugAPI2/api/admin/ClientAPITest.java new file mode 100644 index 0000000..908e98a --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/ClientAPITest.java @@ -0,0 +1,190 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.ClientListParams; +import bookingbugAPI2.models.params.ClientParams; +import bookingbugAPI2.models.params.ClientToggleParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +/** + * Created by sebi on 17.06.2016. + */ +public class ClientAPITest extends AbstractAPITest { + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/client.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void clientList() { + try { + BBCollection clients; + + //All clients + clients = defaultAPI.admin().client().clientList(company, null); + assertNotNull(clients); + + //Paginated clients + clients = defaultAPI.admin().client().clientList(company, new ClientListParams().setPage("1").setPer_page("5")); + assertNotNull(clients); +// assertEquals(clients.size(), 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void clientRead() { + try { + BBCollection clients = defaultAPI.admin().client().clientList(company, new ClientListParams().setPage("1").setPer_page("5")); + assertNotNull(clients); +// assertEquals(clients.size(), 5); + + //Read the first client by id + Client client = defaultAPI.admin().client().clientRead(company, clients.getObjectAtIndex(0).id); + assertNotNull(client); + + //Read the first client by emails + client = defaultAPI.admin().client().clientReadByEmail(company, clients.getObjectAtIndex(0).getEmail()); + assertNotNull(client); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: Remove ignore after 401 bug is solved + @Ignore + @Test + public void clientEditSchema() { + try { + BBCollection clients = defaultAPI.admin().client().clientList(company, new ClientListParams().setPage("1").setPer_page("5")); + assertNotNull(clients); + assertEquals(clients.size(), 5); + + SchemaForm editSchema = defaultAPI.admin().client().getEditClientSchema(clients.getObjectAtIndex(0)); + assertNotNull(editSchema); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: remove ignore after 404 solved (when including email only) + @Ignore + @Test + public void clientEnableDisable() { + try { + BBCollection clients = defaultAPI.admin().client().clientList(company, new ClientListParams().setPage("1").setPer_page("5")); + assertNotNull(clients); + + ClientToggleParams params = new ClientToggleParams() + .setId(clients.getObjectAtIndex(0).id) + .setEmail(null) + .setDisabled(true); + + Client client = defaultAPI.admin().client().clientEnableDisable(company, params); + assertNotNull(client); + + //TODO: assert client is disabled + + params = new ClientToggleParams() + .setId(null) + .setEmail(clients.getObjectAtIndex(0).getEmail()) + .setDisabled(false); + + client = defaultAPI.admin().client().clientEnableDisable(company, params); + assertNotNull(client); + + //TODO: assert client is enabled + + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: Remove ignore after 401 bug is solved + @Ignore + @Test + public void clientUpdate() { + try { + BBCollection clients = defaultAPI.admin().client().clientList(company, new ClientListParams().setPage("1").setPer_page("5")); + assertNotNull(clients); + + DateTime joinDate = new DateTime(); + ClientParams.Update params = new ClientParams.Update() + .setMobile("0323942453") + .setJoin_date(joinDate); + + Client client = defaultAPI.admin().client().clientUpdate(clients.getObjectAtIndex(0), params); + assertNotNull(client); + assertEquals(client.getMobile(), params.getMobile()); + + //TODO: expand here asserts + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: Make call to test env instead of mock + @Test + public void clientCreate() { + try { + MockWebServer server = mockServer(dispatcher); + ClientParams.Create params = new ClientParams.Create() + .setEmail("asd@asd.asd") + .setFirst_name("First name") + .setLast_name("Last name"); + + Client client = mockAPI.admin().client().clientCreate(getCompany(), params); + assertNotNull(client); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/ClinicAPITest.java b/src/test/bookingbugAPI2/api/admin/ClinicAPITest.java new file mode 100644 index 0000000..0384c23 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/ClinicAPITest.java @@ -0,0 +1,131 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.ClinicParams; +import bookingbugAPI2.models.params.Params; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class ClinicAPITest extends AbstractAPITest { + + private Company company; + private Clinic clinic; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/clinic.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + clinic = getClinic(); + } + + @Test + public void clinicList() { + try { + BBCollection clinics; + + //All clinics + clinics = defaultAPI.admin().clinic().clinicList(company, null); + assertNotNull(clinics); + + //Paginated clinics + clinics = defaultAPI.admin().clinic().clinicList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(clinics); + assertTrue(clinics.size() <= 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void clinicUpdate() { + try { + BBCollection clinics = defaultAPI.admin().clinic().clinicList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(clinics); + + ClinicParams.Update params = new ClinicParams.Update() + .setName("Test Name") + .setStartTime(new DateTime("2016-07-15T08:27:23.598Z")); + + if(clinics.size() > 0) { + Clinic clinic = defaultAPI.admin().clinic().clinicUpdate(clinics.getObjectAtIndex(0), params); + assertNotNull(clinic); + assertEquals(clinic.getName(), params.getName()); + assertEquals(clinic.getStartTime(), params.getStartTime()); + } + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void clinicCreate() { + try { + MockWebServer server = mockServer(dispatcher); + ClinicParams.Create params = new ClinicParams.Create() + .setName("string") + .setStartTime(new DateTime("2016-07-11T12:30:32.596Z")); + + Clinic clinic = mockAPI.admin().clinic().clinicCreate(getCompany(), params); + assertNotNull(clinic); + assertEquals(clinic.getName(), params.getName()); + assertEquals(clinic.getStartTime(), params.getStartTime()); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void clinicCancel() { + try { + MockWebServer server = mockServer(dispatcher); + Params params = new Params(); + + Clinic clinic = mockAPI.admin().clinic().clinicCancel(getCompany(), clinicId, params); + assertNotNull(clinic); + // TODO: 15.07.2016 Test clinic cancel. + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} + + diff --git a/src/test/bookingbugAPI2/api/admin/CompanyAPITest.java b/src/test/bookingbugAPI2/api/admin/CompanyAPITest.java new file mode 100644 index 0000000..6219bbf --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/CompanyAPITest.java @@ -0,0 +1,74 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.api.API; +import bookingbugAPI2.api.AbstractAPI; +import bookingbugAPI2.api.AdminAPI; +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.CompanyParams; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Created by sebi on 09.06.2016. + */ +public class CompanyAPITest extends AbstractAPITest{ + + private Company company; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void companyRead() { + assertNotNull(company); + } + + @Test + public void companySettings(){ + try { + CompanySettings companySettings = defaultAPI.admin().company().getSettingsForCompany(company); + assertNotNull(companySettings); + }catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void getCompanyForAdministrator() { + //TODO implement this + } + + @Test + public void getEventsForCompany() { + String authToken = "TOoqPWGtDPa37YkJY8a9Iw"; + String companyURL = "/admin/37048/company"; + + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(authToken); + AdminAPI.CompanyAPI api = new API(config).admin().company(); + + try { + Company company = new Company(api.httpService().api_GET(new URL(api.configService().serverUrl + companyURL))); + + BBCollection events = api.getEventsForCompany(company, new CompanyParams.EventList()); + assertNotNull(events); + assertTrue(events.size() > 0); + } + catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + + } +} diff --git a/src/test/bookingbugAPI2/api/admin/EventAPITest.java b/src/test/bookingbugAPI2/api/admin/EventAPITest.java new file mode 100644 index 0000000..e7a6ee2 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/EventAPITest.java @@ -0,0 +1,30 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.Event; +import bookingbugAPI2.models.HttpException; +import bookingbugAPI2.models.SchemaForm; +import org.junit.Test; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; + +import static org.junit.Assert.assertNotNull; + +/** + * Created by sebi on 29.08.2016. + */ +public class EventAPITest extends AbstractAPITest { + + String authToken = "TOoqPWGtDPa37YkJY8a9Iw"; + String eventLink = "/admin/37048/event_chains/104/events/1048"; + + @Test + public void getNewBookingSchema() throws IOException { + defaultAPI.configService().auth_token = authToken; + Event event = new Event(defaultAPI.httpService().api_GET(new URL(defaultAPI.configService().serverUrl + eventLink))); + + SchemaForm schema = defaultAPI.admin().event().getNewBookingSchema(event); + assertNotNull(schema); + } +} diff --git a/src/test/bookingbugAPI2/api/admin/EventChainAPITest.java b/src/test/bookingbugAPI2/api/admin/EventChainAPITest.java new file mode 100644 index 0000000..b7f71b6 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/EventChainAPITest.java @@ -0,0 +1,212 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.api.API; +import bookingbugAPI2.api.AbstractAPI; +import bookingbugAPI2.api.AdminAPI; +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.EventChainParams; +import bookingbugAPI2.models.params.Params; +import bookingbugAPI2.services.cache.MockCacheService; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class EventChainAPITest extends AbstractAPITest { + + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/event_chain.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void eventChainList() { + try { + BBCollection eventChains; + + //All eventChains + eventChains = defaultAPI.admin().eventChain().eventChainList(company, null); + assertNotNull(eventChains); + + //Paginated eventChains + eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventChains); + assertTrue(eventChains.size() <= 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainRead() { + try { + BBCollection eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventChains); + assertTrue(eventChains.size() <= 5); + + //Read the first eventChain by id + if(eventChains.size() > 0) { + EventChain eventChain = defaultAPI.admin().eventChain().eventChainRead(company, eventChains.getObjectAtIndex(0).id); + assertNotNull(eventChain); + } + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainReadUsingRefId() { + try { + BBCollection eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventChains); + assertTrue(eventChains.size() <= 5); + + // TODO: 12.07.2016 Read the eventChain by ref id + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainNewSchema() { + try { + // TODO: 12.07.2016 test new event chain git stat + BBCollection eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params()); + assertNotNull(eventChains); + + SchemaForm editSchema = defaultAPI.admin().eventChain().getNewEventChainSchema(company); + assertNotNull(editSchema); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainEditSchema() { + try { + BBCollection eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventChains); + assertTrue(eventChains.size() <= 5); + + if(eventChains.size() > 0) { + SchemaForm editSchema = defaultAPI.admin().eventChain().getEditEventChainSchema(company, eventChains.getObjectAtIndex(0).id); + assertNotNull(editSchema); + } + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainUpdate() { + try { + BBCollection eventChains = defaultAPI.admin().eventChain().eventChainList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventChains); + + EventChainParams.Update params = new EventChainParams.Update() + .setName("Test") + .setDescription("Test Description"); + + if(eventChains.size() > 0) { + EventChain eventChain = defaultAPI.admin().eventChain().eventChainUpdate(eventChains.getObjectAtIndex(0), params); + assertNotNull(eventChain); + assertEquals(eventChain.getName(), params.getName()); + assertEquals(eventChain.getDescription(), params.getDescription()); + //TODO: expand here asserts + } + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventChainCreate() { + try { + MockWebServer server = mockServer(dispatcher); + EventChainParams.Create params = new EventChainParams.Create() + .setAddressId(240123) + .setName("First name") + .setDatetime("2014-04-14"); + + EventChain eventChain = mockAPI.admin().eventChain().eventChainCreate(getCompany(), params); + assertNotNull(eventChain); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void getEventsForEventChain() { + String authToken = "TOoqPWGtDPa37YkJY8a9Iw"; + String eventChainLink = "/admin/37048/event_chains/104"; + + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withAuthToken(authToken); + + AdminAPI.EventChainAPI api = new API(config).admin().eventChain(); + + try { + EventChain eventChain = new EventChain( + api.httpService().api_GET(new URL(defaultAPI.configService().serverUrl + eventChainLink))); + + assertNotNull(eventChain); + + BBCollection events = api.getEventsForEventChain(eventChain, new Params()); + assertNotNull(events); + assertTrue(events.size() > 0); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + + + } + +} diff --git a/src/test/bookingbugAPI2/api/admin/EventGroupAPITest.java b/src/test/bookingbugAPI2/api/admin/EventGroupAPITest.java new file mode 100644 index 0000000..e4ba045 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/EventGroupAPITest.java @@ -0,0 +1,114 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.Params; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class EventGroupAPITest extends AbstractAPITest { + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/event_chain.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void eventGroupList() { + try { + BBCollection eventGroups; + + //All eventGroups + eventGroups = defaultAPI.admin().eventGroup().eventGroupList(company, null); + assertNotNull(eventGroups); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventGroupRead() { + try { + BBCollection eventGroups = defaultAPI.admin().eventGroup().eventGroupList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventGroups); + assertTrue(eventGroups.size() <= 5); + + if(eventGroups.size() > 0) { + //Read the first eventGroup by id + EventGroup eventGroup = defaultAPI.admin().eventGroup().eventGroupRead(company, eventGroups.getObjectAtIndex(0).id); + assertNotNull(eventGroup); + } + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventGroupNewSchema() { + try { + // TODO: 12.07.2016 test new event chain git stat + BBCollection eventGroups = defaultAPI.admin().eventGroup().eventGroupList(company, new Params()); + assertNotNull(eventGroups); + + SchemaForm editSchema = defaultAPI.admin().eventGroup().getNewEventGroupSchema(company); + assertNotNull(editSchema); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void eventGroupEditSchema() { + try { + BBCollection eventGroups = defaultAPI.admin().eventGroup().eventGroupList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(eventGroups); + assertTrue(eventGroups.size() <= 5); + + if (eventGroups.size() > 0) { + SchemaForm editSchema = defaultAPI.admin().eventGroup().getEditEventGroupSchema(company, eventGroups.getObjectAtIndex(0).id); + assertNotNull(editSchema); + } + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/LoginAPITest.java b/src/test/bookingbugAPI2/api/admin/LoginAPITest.java new file mode 100644 index 0000000..ad81029 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/LoginAPITest.java @@ -0,0 +1,85 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.api.AdminURLS; +import bookingbugAPI2.models.Administrator; +import bookingbugAPI2.models.Login; +import bookingbugAPI2.models.ModelTest; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.*; + +/** + * Created by sebi on 19.08.2016. + */ +public class LoginAPITest extends AbstractAPITest { + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if (Objects.equals(request.getMethod(), "POST") && request.getBodySize() != 0) { + String body = request.getBody().readUtf8(); + JsonNode resp; + if(body.contains("email=sebii%40assist.ro")) { + resp = ModelTest.getJSON("json/simple_login.json"); + return new MockResponse().setResponseCode(200).setBody(resp.toString()); + } else { + resp = ModelTest.getJSON("json/multiple_login.json"); + return new MockResponse().setResponseCode(400).setBody(resp.toString()); + } + } + + return new MockResponse().setResponseCode(404).setBody("{}"); + } + }; + + @Test + public void auth() throws IOException { + MockWebServer server = mockServer(dispatcher); + + //Test simple login + Login login = mockAPI.admin().login().auth("sebii@assist.ro", "Assist123"); + assertNotNull(login); + assertNotNull(login.getAuthToken()); + + //Test multiple login (multiple companies) + login = mockAPI.admin().login().auth("sebi+2@assist.ro", "Assist123"); + assertNotNull(login); + assertNull(login.getAuthToken()); + assertTrue(login.isMultiLogin()); + + server.shutdown(); + } + + @Test + public void authWithCompanyAdministrator() throws IOException { + MockWebServer server = mockServer(dispatcher); + + //Test multiple login (multiple companies) + Login login = mockAPI.admin().login().auth("sebi+2@assist.ro", "Assist123"); + assertNotNull(login); + assertNull(login.getAuthToken()); + assertTrue(login.isMultiLogin()); + + for(Administrator administrator : login.getAdministrators()) { + //Login with each company. Change email to get the simple_login + Login adminLogin = mockAPI.admin().login().authWithCompanyAdministrator(administrator, "sebii@assist.ro", "Assist123"); + assertNotNull(adminLogin); + assertNotNull(adminLogin.getAuthToken()); + assertFalse(adminLogin.isMultiLogin()); + } + + server.shutdown(); + } +} diff --git a/src/test/bookingbugAPI2/api/admin/PersonAPITest.java b/src/test/bookingbugAPI2/api/admin/PersonAPITest.java new file mode 100644 index 0000000..824ac24 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/PersonAPITest.java @@ -0,0 +1,134 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.Params; +import bookingbugAPI2.models.params.PersonParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class PersonAPITest extends AbstractAPITest{ + + private Company company; + private Person person; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/person.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + person = getPerson(); + } + + @Test + public void PersonList() { + try { + BBCollection people; + + //All people + people = defaultAPI.admin().person().personList(company, null); + assertNotNull(people); + + //Paginated people + people = defaultAPI.admin().person().personList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(people); + assertTrue(people.size() <= 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void PersonUpdate() { + try { + BBCollection people = defaultAPI.admin().person().personList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(people); + + PersonParams.Update params = new PersonParams.Update() + .setName("Test Name") + .setDescription("Test Description"); + + Person Person = defaultAPI.admin().person().personUpdate(company, people.getObjectAtIndex(0).id, params); + assertNotNull(Person); + assertEquals(Person.getName(), params.getName()); + assertEquals(Person.getDescription(), params.getDescription()); + + //TODO: expand here asserts + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void PersonCreate() { + try { + MockWebServer server = mockServer(dispatcher); + PersonParams.Create params = new PersonParams.Create() + .setName("Barry") + .setDescription(""); + + Person person = mockAPI.admin().person().personCreate(getCompany(), params); + assertNotNull(person); + assertEquals(person.getName(), params.getName()); + assertEquals(person.getDescription(), params.getDescription()); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void PersonNewSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().person().getNewPersonSchema(company); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void PersonEditSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().person().getEditPersonSchema(person); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/PurchaseAPITest.java b/src/test/bookingbugAPI2/api/admin/PurchaseAPITest.java new file mode 100644 index 0000000..340e045 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/PurchaseAPITest.java @@ -0,0 +1,97 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.PurchaseListParams; +import bookingbugAPI2.models.params.PurchaseParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.joda.time.DateTime; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class PurchaseAPITest extends AbstractAPITest { + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/purchase.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void purchaseList() { + try { + BBCollection purchases; + + //All purchases + purchases = defaultAPI.admin().purchase().purchaseList(company, new PurchaseListParams().setCreated_from(new DateTime("2016-07-11T12:30:32.596Z"))); + assertNotNull(purchases); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void purchaseRead() { + try { + BBCollection purchases = defaultAPI.admin().purchase().purchaseList(company, new PurchaseListParams().setCreated_from(new DateTime("2016-07-11T12:30:32.596Z"))); + assertNotNull(purchases); + + Purchase purchase = defaultAPI.admin().purchase().purchaseRead(company, purchases.getObjectAtIndex(0).id); + assertNotNull(purchase); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void purchasePay() { + try { + MockWebServer server = mockServer(dispatcher); + BBCollection purchases = defaultAPI.admin().purchase().purchaseList(company, new PurchaseListParams().setCreated_from(new DateTime("2016-07-11T12:30:32.596Z"))); + assertNotNull(purchases); + + PurchaseParams params = new PurchaseParams() + .setPaymentStatus("paid"); + + Purchase purchase = mockAPI.admin().purchase().purchasePay(company, purchases.getObjectAtIndex(0).id, params); + server.shutdown(); + // TODO: 18.07.2016 Complete purchasePay() test + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/QuestionAPITest.java b/src/test/bookingbugAPI2/api/admin/QuestionAPITest.java new file mode 100644 index 0000000..b52322c --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/QuestionAPITest.java @@ -0,0 +1,60 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.BBCollection; +import bookingbugAPI2.models.Company; +import bookingbugAPI2.models.ModelTest; +import bookingbugAPI2.models.Question; +import bookingbugAPI2.models.params.QuestionListParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertNotNull; + + +public class QuestionAPITest extends AbstractAPITest { + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/question.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + //TODO: Add detail_group_id + @Ignore + @Test + public void questionList() { + try { + BBCollection questions = defaultAPI.admin().question().questionList(company, new QuestionListParams()); + assertNotNull(questions); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/ResourceAPITest.java b/src/test/bookingbugAPI2/api/admin/ResourceAPITest.java new file mode 100644 index 0000000..529a128 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/ResourceAPITest.java @@ -0,0 +1,136 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.Params; +import bookingbugAPI2.models.params.ResourceParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Test; + +import java.util.Objects; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + + +public class ResourceAPITest extends AbstractAPITest { + + private Company company; + private Resource resource; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if( (Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/resource.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + resource = getResource(); + } + + @Test + public void resourceList() { + try { + BBCollection resources; + + //All services + resources = defaultAPI.admin().resource().resourceList(company, null); + assertNotNull(resources); + + //Paginated services + resources = defaultAPI.admin().resource().resourceList(company, new Params<>().setPage(1).setPerPage(5)); + assertNotNull(resources); + assertTrue(resources.size() <= 5); + + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void resourceRead() { + try { + Resource resource = defaultAPI.admin().resource().resourceRead(company, resourceId); + assertNotNull(resource); + + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void resourceCreate() { + try { + MockWebServer server = mockServer(dispatcher); + ResourceParams.Create params = new ResourceParams.Create() + .setName("test resource") + .setDescription("adfasd asd"); + Resource resource = mockAPI.admin().resource().resourceCreate(company, params); + + assertNotNull(resource); + server.shutdown(); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void resourceUpdate() { + try { + MockWebServer server = mockServer(dispatcher); + ResourceParams.Update params = new ResourceParams.Update() + .setName("update resource") + .setDescription("dsfg asd"); + Resource updatedResource = mockAPI.admin().resource().resourceUpdate(resource, params); + assertNotNull(updatedResource); + server.shutdown(); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void resourceNewSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().resource().getNewResourceSchema(company); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void resourceEditSchema() { + try { + SchemaForm schemaForm = defaultAPI.admin().resource().getEditResourceSchema(resource); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/ScheduleAPITest.java b/src/test/bookingbugAPI2/api/admin/ScheduleAPITest.java new file mode 100644 index 0000000..0511471 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/ScheduleAPITest.java @@ -0,0 +1,172 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.Params; +import bookingbugAPI2.models.params.ScheduleParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + + +public class ScheduleAPITest extends AbstractAPITest { + + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/schedule.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void scheduleList() { + try { + BBCollection schedules; + + //All schedules + schedules = defaultAPI.admin().schedule().scheduleList(company, null); + assertNotNull(schedules); + + //Paginated schedules + schedules = defaultAPI.admin().schedule().scheduleList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(schedules); + assertEquals(schedules.size(), 5); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleRead() { + try { + BBCollection schedules = defaultAPI.admin().schedule().scheduleList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(schedules); + assertEquals(schedules.size(), 5); + + //Read the first schedule by id + Schedule schedule = defaultAPI.admin().schedule().scheduleRead(company, schedules.getObjectAtIndex(0).id); + assertNotNull(schedule); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleNewSchema() { + try { + // TODO: 12.07.2016 test new event chain git stat + BBCollection schedules = defaultAPI.admin().schedule().scheduleList(company, new Params()); + assertNotNull(schedules); + + SchemaForm editSchema = defaultAPI.admin().schedule().getNewScheduleSchema(company); + assertNotNull(editSchema); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleEditSchema() { + try { + BBCollection schedules = defaultAPI.admin().schedule().scheduleList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(schedules); + assertEquals(schedules.size(), 5); + + /* SchemaForm editSchema = defaultAPI.admin().schedule().getEditScheduleSchema(company, schedules.getObjectAtIndex(0).id); + assertNotNull(editSchema);*/ + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleUpdate() { + try { + BBCollection schedules = defaultAPI.admin().schedule().scheduleList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(schedules); + + ScheduleParams.Update params = new ScheduleParams.Update() + .setName("Test") + .setDesc("Test Description"); + + /*Schedule schedule = defaultAPI.admin().schedule().scheduleUpdate(company, schedules.getObjectAtIndex(0), params); + assertNotNull(schedule); + assertEquals(schedule.getName(), params.getName()); + assertEquals(schedule.getDesc(), params.getDesc());*/ + + //TODO: expand here asserts + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleCreate() { + try { + MockWebServer server = mockServer(dispatcher); + ScheduleParams.Create params = new ScheduleParams.Create() + .setName("First name") + .setDesc("Description"); + + Schedule schedule = mockAPI.admin().schedule().scheduleCreate(getCompany(), params); + assertNotNull(schedule); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void scheduleDelete() { + try { + MockWebServer server = mockServer(dispatcher); + + BBCollection schedules = defaultAPI.admin().schedule().scheduleList(company, new Params().setPage(1).setPerPage(5)); + assertNotNull(schedules); + + // TODO: 13.07.2016 test delete schedule + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/ServiceAPITest.java b/src/test/bookingbugAPI2/api/admin/ServiceAPITest.java new file mode 100644 index 0000000..b919c5f --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/ServiceAPITest.java @@ -0,0 +1,168 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.ServiceListParams; +import bookingbugAPI2.models.params.ServiceParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Created by sebi on 10.06.2016. + */ +public class ServiceAPITest extends AbstractAPITest { + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if( (Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/service.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void serviceList() { + try { + BBCollection services; + + //All services + services = defaultAPI.admin().service().serviceList(company, null); + assertNotNull(services); + + //Paginated services + services = defaultAPI.admin().service().serviceList(company, new ServiceListParams().setPage(1).setPerPage(5)); + assertNotNull(services); + assertTrue(services.size() <= 5); + + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void serviceRead() { + try { + //All services + BBCollection services = defaultAPI.admin().service().serviceList(company, null); + Service service = defaultAPI.admin().service().serviceRead(company, services.getObjectAtIndex(0).id); + assertNotNull(service); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + + + } + } + + @Test + public void serviceCreate() { + try { + MockWebServer server = mockServer(dispatcher); + ServiceParams.ServiceCreateParams params = new ServiceParams.ServiceCreateParams() + .setName("Test service") + .setReference("ref") + .setSpaces(15) + .setDuration(45); + + Service service = mockAPI.admin().service().serviceCreate(getCompany(), params); + assertNotNull(service); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void serviceUpdate() { + try { + JsonNode serviceJson = ModelTest.getJSON("json/service.json"); + Service service = new Service(new HttpServiceResponse(Utils.stringToContentRep(serviceJson.toString()))); + MockWebServer server = mockServer(dispatcher); + ServiceParams.ServiceUpdateParams params = new ServiceParams.ServiceUpdateParams() + .setName("Test service") + .setReference("ref") + .setDuration(45); + + Service updatedService = mockAPI.admin().service().serviceUpdate(service, params); + assertNotNull(updatedService); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void serviceNewSchema() { + try { + //Paginated services + SchemaForm schemaForm = defaultAPI.admin().service().getNewServiceSchema(company); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void serviceEditSchema() { + try { + //Paginated services + BBCollection services = defaultAPI.admin().service().serviceList(company, null); + SchemaForm schemaForm = defaultAPI.admin().service().getEditServiceSchema(services.getObjectAtIndex(0)); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + //TODO: Remove ignore when 401 Forbidden is solved + @Test + @Ignore + public void serviceNewBookingSchema() { + try { + //Paginated services + BBCollection services = defaultAPI.admin().service().serviceList(company, null); + SchemaForm schemaForm = defaultAPI.admin().service().getNewBookingSchema(services.getObjectAtIndex(0)); + assertNotNull(schemaForm); + }catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + +} diff --git a/src/test/bookingbugAPI2/api/admin/SessionAPITest.java b/src/test/bookingbugAPI2/api/admin/SessionAPITest.java new file mode 100644 index 0000000..0191d5a --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/SessionAPITest.java @@ -0,0 +1,74 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.BBCollection; +import bookingbugAPI2.models.Company; +import bookingbugAPI2.models.ModelTest; +import bookingbugAPI2.models.Session; +import bookingbugAPI2.models.params.SessionListParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertNotNull; + +//TODO: Find company with session +@Ignore +public class SessionAPITest extends AbstractAPITest { + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/session.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void sessionList() { + try { + BBCollection sessions = defaultAPI.admin().session().sessionList(company, new SessionListParams()); + assertNotNull(sessions); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void sessionRead() { + try { + BBCollection sessions = defaultAPI.admin().session().sessionList(company, new SessionListParams()); + assertNotNull(sessions); + + Session session = defaultAPI.admin().session().sessionRead(company, sessions.getObjectAtIndex(0).id); + assertNotNull(session); + + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI2/api/admin/SlotAPITest.java b/src/test/bookingbugAPI2/api/admin/SlotAPITest.java new file mode 100644 index 0000000..cd1ba57 --- /dev/null +++ b/src/test/bookingbugAPI2/api/admin/SlotAPITest.java @@ -0,0 +1,140 @@ +package bookingbugAPI2.api.admin; + +import bookingbugAPI2.models.*; +import bookingbugAPI2.models.params.SlotListParams; +import bookingbugAPI2.models.params.SlotParams; +import com.fasterxml.jackson.databind.JsonNode; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.IOException; +import java.util.Objects; + +import static org.junit.Assert.assertNotNull; + +//TODO: Find company with slots +@Ignore +public class SlotAPITest extends AbstractAPITest { + + private Company company; + + //Dispatcher for create/update + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post/put data + if ((Objects.equals(request.getMethod(), "POST") || Objects.equals(request.getMethod(), "PUT")) && request.getBodySize() != 0) { + JsonNode resp = ModelTest.getJSON("json/slot.json"); + return new MockResponse().setResponseCode(201).setBody(resp.toString()); + } + + return new MockResponse().setResponseCode(400).setBody("{}"); + } + }; + + @Override + @Before + public void setUp() { + super.setUp(); + company = getCompany(); + } + + @Test + public void slotList() { + try { + BBCollection slots; + + //All slots + slots = defaultAPI.admin().slot().slotList(company, new SlotListParams()); + assertNotNull(slots); + + //Paginated slots + slots = defaultAPI.admin().slot().slotList(company, new SlotListParams()); + assertNotNull(slots); + + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void slotRead() { + try { + //All slots + BBCollection slots = defaultAPI.admin().slot().slotList(company, new SlotListParams()); + assertNotNull(slots); + + if(slots.size() > 0) { + Slot slot = defaultAPI.admin().slot().slotRead(company, slots.getObjectAtIndex(0).id); + assertNotNull(slot); + } + } catch (Exception e) { + e.printStackTrace(); + assert false : e; + + + } + } + + @Test + public void slotCreate() { + try { + MockWebServer server = mockServer(dispatcher); + SlotParams.Create params = new SlotParams.Create() + .setStartTime("19/07/2016") + .setEndTime("20/07/2016"); + + Slot slot = mockAPI.admin().slot().slotCreate(getCompany(), params); + assertNotNull(slot); + + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Ignore + @Test + public void slotUpdate() { + try { + JsonNode slotJson = ModelTest.getJSON("json/slot.json"); + Slot slot = new Slot(new HttpServiceResponse(Utils.stringToContentRep(slotJson.toString()))); + MockWebServer server = mockServer(dispatcher); + SlotParams.Update params = new SlotParams.Update() + .setStartTime("19/07/2016") + .setEndTime("20/07/2016"); + + Slot updatedService = mockAPI.admin().slot().slotUpdate(slot, params); + assertNotNull(updatedService); + server.shutdown(); + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } + + @Test + public void slotDelete() { + try { + MockWebServer server = mockServer(dispatcher); + + BBCollection slots = defaultAPI.admin().slot().slotList(company, new SlotListParams()); + assertNotNull(slots); + // TODO: 19.07.2016 Test slotDelete + } catch (IOException e) { + e.printStackTrace(); + assert false : e; + } + } +} diff --git a/src/test/bookingbugAPI/models/AddressTest.java b/src/test/bookingbugAPI2/models/AddressTest.java similarity index 95% rename from src/test/bookingbugAPI/models/AddressTest.java rename to src/test/bookingbugAPI2/models/AddressTest.java index 4ffafc7..2a9b568 100644 --- a/src/test/bookingbugAPI/models/AddressTest.java +++ b/src/test/bookingbugAPI2/models/AddressTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/AdminTest.java b/src/test/bookingbugAPI2/models/AdminTest.java similarity index 95% rename from src/test/bookingbugAPI/models/AdminTest.java rename to src/test/bookingbugAPI2/models/AdminTest.java index baf9787..ea8dd1c 100644 --- a/src/test/bookingbugAPI/models/AdminTest.java +++ b/src/test/bookingbugAPI2/models/AdminTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/AnswerTest.java b/src/test/bookingbugAPI2/models/AnswerTest.java similarity index 94% rename from src/test/bookingbugAPI/models/AnswerTest.java rename to src/test/bookingbugAPI2/models/AnswerTest.java index e5778ff..0648882 100644 --- a/src/test/bookingbugAPI/models/AnswerTest.java +++ b/src/test/bookingbugAPI2/models/AnswerTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/BasketItemTest.java b/src/test/bookingbugAPI2/models/BasketItemTest.java similarity index 95% rename from src/test/bookingbugAPI/models/BasketItemTest.java rename to src/test/bookingbugAPI2/models/BasketItemTest.java index cb094c8..f9e37c3 100644 --- a/src/test/bookingbugAPI/models/BasketItemTest.java +++ b/src/test/bookingbugAPI2/models/BasketItemTest.java @@ -1,14 +1,13 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.io.IOException; import java.text.ParseException; import static org.junit.Assert.assertTrue; diff --git a/src/test/bookingbugAPI/models/BasketTest.java b/src/test/bookingbugAPI2/models/BasketTest.java similarity index 94% rename from src/test/bookingbugAPI/models/BasketTest.java rename to src/test/bookingbugAPI2/models/BasketTest.java index 6ed52f7..65c1a08 100644 --- a/src/test/bookingbugAPI/models/BasketTest.java +++ b/src/test/bookingbugAPI2/models/BasketTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/BookingTest.java b/src/test/bookingbugAPI2/models/BookingTest.java similarity index 98% rename from src/test/bookingbugAPI/models/BookingTest.java rename to src/test/bookingbugAPI2/models/BookingTest.java index 172dfc9..88bcb16 100644 --- a/src/test/bookingbugAPI/models/BookingTest.java +++ b/src/test/bookingbugAPI2/models/BookingTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; diff --git a/src/test/bookingbugAPI/models/ClientTest.java b/src/test/bookingbugAPI2/models/ClientTest.java similarity index 96% rename from src/test/bookingbugAPI/models/ClientTest.java rename to src/test/bookingbugAPI2/models/ClientTest.java index 09c95f9..ac43904 100644 --- a/src/test/bookingbugAPI/models/ClientTest.java +++ b/src/test/bookingbugAPI2/models/ClientTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI2/models/ClinicTest.java b/src/test/bookingbugAPI2/models/ClinicTest.java new file mode 100644 index 0000000..4cedc9e --- /dev/null +++ b/src/test/bookingbugAPI2/models/ClinicTest.java @@ -0,0 +1,43 @@ +package bookingbugAPI2.models; + +import com.fasterxml.jackson.databind.JsonNode; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.joda.time.DateTime; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.text.ParseException; + +import static org.junit.Assert.assertTrue; + + +public class ClinicTest extends ModelTest { + private JsonNode jsonNode; + + @Override + @Before + public void setUp() { + jsonNode = getJSON("json/clinic.json"); + } + + @Override + @Test + public void modelInit() throws ParseException { + Clinic clinic = new Clinic(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); + + assertTrue(clinic.getName().equals(jsonNode.get("name").textValue())); + assertTrue(clinic.getStartTime().equals(new DateTime(jsonNode.get("start_time").textValue()))); + assertTrue(clinic.getEndTime().equals(new DateTime(jsonNode.get("end_time").textValue()))); + assertTrue(compareLists(clinic.getResourceIds(),jsonNode.toString(),"resource_ids")); + assertTrue(compareLists(clinic.getPersonIds(),jsonNode.toString(),"person_ids")); + assertTrue(compareLists(clinic.getServiceIds(),jsonNode.toString(),"service_ids")); + } + + @Override + @After + public void tearDown() { + jsonNode = null; + } +} diff --git a/src/test/bookingbugAPI/models/CompanyTest.java b/src/test/bookingbugAPI2/models/CompanyTest.java similarity index 97% rename from src/test/bookingbugAPI/models/CompanyTest.java rename to src/test/bookingbugAPI2/models/CompanyTest.java index c632fe5..8abe7d2 100644 --- a/src/test/bookingbugAPI/models/CompanyTest.java +++ b/src/test/bookingbugAPI2/models/CompanyTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -75,7 +75,7 @@ public void modelInit() throws ParseException { assertTrue(company.getSpaceStatusesLink().equals(jsonLinks.get("space_statuses").get("href").textValue())); assertTrue(company.getNewPersonLink().equals(jsonLinks.get("new_person").get("href").textValue())); assertTrue(company.getNewResourceLink().equals(jsonLinks.get("new_resource").get("href").textValue())); - assertTrue(company.getSchedules().equals(jsonLinks.get("schedules").get("href").textValue())); + assertTrue(company.getSchedulesLink().equals(jsonLinks.get("schedules").get("href").textValue())); assertTrue(company.getNewScheduleLink().equals(jsonLinks.get("new_schedule").get("href").textValue())); assertTrue(company.getAdministratorsLink().equals(jsonLinks.get("administrators").get("href").textValue())); assertTrue(company.getNewAdministratorLink().equals(jsonLinks.get("new_administrator").get("href").textValue())); diff --git a/src/test/bookingbugAPI/models/CouponTest.java b/src/test/bookingbugAPI2/models/CouponTest.java similarity index 95% rename from src/test/bookingbugAPI/models/CouponTest.java rename to src/test/bookingbugAPI2/models/CouponTest.java index 50fa3e3..ad39196 100644 --- a/src/test/bookingbugAPI/models/CouponTest.java +++ b/src/test/bookingbugAPI2/models/CouponTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; diff --git a/src/test/bookingbugAPI/models/DealTest.java b/src/test/bookingbugAPI2/models/DealTest.java similarity index 94% rename from src/test/bookingbugAPI/models/DealTest.java rename to src/test/bookingbugAPI2/models/DealTest.java index f447735..a71265f 100644 --- a/src/test/bookingbugAPI/models/DealTest.java +++ b/src/test/bookingbugAPI2/models/DealTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; diff --git a/src/test/bookingbugAPI/models/EventChainTest.java b/src/test/bookingbugAPI2/models/EventChainTest.java similarity index 96% rename from src/test/bookingbugAPI/models/EventChainTest.java rename to src/test/bookingbugAPI2/models/EventChainTest.java index 9f27e6b..9091b9e 100644 --- a/src/test/bookingbugAPI/models/EventChainTest.java +++ b/src/test/bookingbugAPI2/models/EventChainTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.joda.time.DateTime; import org.junit.After; import org.junit.Before; diff --git a/src/test/bookingbugAPI/models/EventGroupTest.java b/src/test/bookingbugAPI2/models/EventGroupTest.java similarity index 92% rename from src/test/bookingbugAPI/models/EventGroupTest.java rename to src/test/bookingbugAPI2/models/EventGroupTest.java index e1bd440..235764b 100644 --- a/src/test/bookingbugAPI/models/EventGroupTest.java +++ b/src/test/bookingbugAPI2/models/EventGroupTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/EventTest.java b/src/test/bookingbugAPI2/models/EventTest.java similarity index 94% rename from src/test/bookingbugAPI/models/EventTest.java rename to src/test/bookingbugAPI2/models/EventTest.java index 8bd6634..e7595e5 100644 --- a/src/test/bookingbugAPI/models/EventTest.java +++ b/src/test/bookingbugAPI2/models/EventTest.java @@ -1,55 +1,55 @@ -package bookingbugAPI.models; - -import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; -import org.joda.time.DateTime; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.junit.Assert.assertTrue; - -public class EventTest extends ModelTest { - - private JsonNode jsonNode; - - @Override - @Before - public void setUp() { - jsonNode = getJSON("json/event.json"); - } - - @Override - @Test - public void modelInit() throws java.text.ParseException { - Event event = new Event(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); - JsonNode jsonLinks = jsonNode.get("_links"); - - assertTrue(event.getId().equals(jsonNode.get("id").intValue())); - assertTrue(event.getDatetime().equals(new DateTime(jsonNode.get("datetime").textValue()))); - assertTrue(event.getDescription().equals(jsonNode.get("description").textValue())); - assertTrue(event.getStatus().equals(jsonNode.get("status").intValue())); - assertTrue(event.getSpacesHeld().equals(jsonNode.get("spaces_held").intValue())); - assertTrue(event.getSpacesBooked().equals(jsonNode.get("spaces_booked").intValue())); - assertTrue(event.getSpacesReserved().equals(jsonNode.get("spaces_reserved").intValue())); - assertTrue(event.getSpacesBlocked().equals(jsonNode.get("spaces_blocked").intValue())); - assertTrue(event.getNumSpaces().equals(jsonNode.get("num_spaces").intValue())); - assertTrue(event.getSpacesWait().equals(jsonNode.get("spaces_wait").intValue())); - assertTrue(event.getEventChainId().equals(jsonNode.get("event_chain_id").intValue())); - assertTrue(event.getServiceId().equals(jsonNode.get("service_id").intValue())); - assertTrue(event.getDuration().equals(jsonNode.get("duration").intValue())); - assertTrue(event.getPrice().equals(jsonNode.get("price").intValue())); - assertTrue(event.getEventGroupsLink().equals((jsonLinks.get("event_groups")).get("href").textValue())); - assertTrue(event.getEventChainsLink().equals((jsonLinks.get("event_chains")).get("href").textValue())); - assertTrue(event.getBookLink().equals((jsonLinks.get("book")).get("href").textValue())); - // TODO: 01.06.2016 Implement and Test getTicketSpaces() - } - - @Override - @After - public void tearDown() { - jsonNode = null; - } - -} +package bookingbugAPI2.models; + +import com.fasterxml.jackson.databind.JsonNode; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.joda.time.DateTime; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +public class EventTest extends ModelTest { + + private JsonNode jsonNode; + + @Override + @Before + public void setUp() { + jsonNode = getJSON("json/event.json"); + } + + @Override + @Test + public void modelInit() throws java.text.ParseException { + Event event = new Event(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); + JsonNode jsonLinks = jsonNode.get("_links"); + + assertTrue(event.getId().equals(jsonNode.get("id").intValue())); + assertTrue(event.getDatetime().equals(new DateTime(jsonNode.get("datetime").textValue()))); + assertTrue(event.getDescription().equals(jsonNode.get("description").textValue())); + assertTrue(event.getStatus().equals(jsonNode.get("status").intValue())); + assertTrue(event.getSpacesHeld().equals(jsonNode.get("spaces_held").intValue())); + assertTrue(event.getSpacesBooked().equals(jsonNode.get("spaces_booked").intValue())); + assertTrue(event.getSpacesReserved().equals(jsonNode.get("spaces_reserved").intValue())); + assertTrue(event.getSpacesBlocked().equals(jsonNode.get("spaces_blocked").intValue())); + assertTrue(event.getNumSpaces().equals(jsonNode.get("num_spaces").intValue())); + assertTrue(event.getSpacesWait().equals(jsonNode.get("spaces_wait").intValue())); + assertTrue(event.getEventChainId().equals(jsonNode.get("event_chain_id").intValue())); + assertTrue(event.getServiceId().equals(jsonNode.get("service_id").intValue())); + assertTrue(event.getDuration().equals(jsonNode.get("duration").intValue())); + assertTrue(event.getPrice().equals(jsonNode.get("price").intValue())); + assertTrue(event.getEventGroupsLink().equals((jsonLinks.get("event_groups")).get("href").textValue())); + assertTrue(event.getEventChainsLink().equals((jsonLinks.get("event_chains")).get("href").textValue())); + assertTrue(event.getBookLink().equals((jsonLinks.get("book")).get("href").textValue())); + // TODO: 01.06.2016 Implement and Test getTicketSpaces() + } + + @Override + @After + public void tearDown() { + jsonNode = null; + } + +} diff --git a/src/test/bookingbugAPI/models/LoginTest.java b/src/test/bookingbugAPI2/models/LoginTest.java similarity index 93% rename from src/test/bookingbugAPI/models/LoginTest.java rename to src/test/bookingbugAPI2/models/LoginTest.java index bf3b598..af342e1 100644 --- a/src/test/bookingbugAPI/models/LoginTest.java +++ b/src/test/bookingbugAPI2/models/LoginTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/MemberTest.java b/src/test/bookingbugAPI2/models/MemberTest.java similarity index 97% rename from src/test/bookingbugAPI/models/MemberTest.java rename to src/test/bookingbugAPI2/models/MemberTest.java index a8f78d5..a1e87b1 100644 --- a/src/test/bookingbugAPI/models/MemberTest.java +++ b/src/test/bookingbugAPI2/models/MemberTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/ModelTest.java b/src/test/bookingbugAPI2/models/ModelTest.java similarity index 85% rename from src/test/bookingbugAPI/models/ModelTest.java rename to src/test/bookingbugAPI2/models/ModelTest.java index 5862b43..672232a 100644 --- a/src/test/bookingbugAPI/models/ModelTest.java +++ b/src/test/bookingbugAPI2/models/ModelTest.java @@ -1,91 +1,88 @@ -package bookingbugAPI.models; - -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.theoryinpractise.halbuilder.api.Link; -import com.theoryinpractise.halbuilder.api.RepresentationException; -import org.junit.After; -import org.junit.Before; -import org.junit.Ignore; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.List; - -/** - * Abstract ModelTest class. Must be inherited by all tests for bb models - * Has setUp, tearDown and modelInit methods - */ -@Ignore -public abstract class ModelTest { - - @Before - public abstract void setUp(); - - @Test - public abstract void modelInit() throws ParseException; - - @After - public abstract void tearDown(); - - public JsonNode getJSON(String jsonFile) { - ClassLoader classLoader = getClass().getClassLoader(); - String fileName; - try { - fileName = classLoader.getResource(jsonFile).getFile(); - ObjectMapper mapper = new ObjectMapper(); - return mapper.readTree(new File(fileName)); - } catch (IOException e) { - e.printStackTrace(); - } - - return null; - } - - public boolean compareLists(List list, String json, String key) { - try { - JsonNode jsonArray = new ObjectMapper().readTree(json).get(key); - if (jsonArray.isArray()) { - for (JsonNode objNode : jsonArray) { - boolean eq = false; - for (T item : list) { - if (objNode.asText().equals(item.toString())) { - eq = true; - break; - } - } - if (!eq) { - return false; - } - } - } - } catch (IOException e) { - e.printStackTrace(); - return false; - } - return true; - } - - public List getLinksHref(String json, String key) { - List vals = null; - - try { - vals = new ArrayList<>(); - - JsonNode jsonArray = new ObjectMapper().readTree(json).get(key); - if (jsonArray.isArray()) { - for (final JsonNode objNode : jsonArray) { - vals.add(objNode.get("href").textValue()); - } - } - } catch (IOException e) { - e.printStackTrace(); - } - - return vals; - } -} +package bookingbugAPI2.models; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; + +import java.io.File; +import java.io.IOException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.List; + +/** + * Abstract ModelTest class. Must be inherited by all tests for bb models + * Has setUp, tearDown and modelInit methods + */ +@Ignore +public abstract class ModelTest { + + @Before + public abstract void setUp(); + + @Test + public abstract void modelInit() throws ParseException; + + @After + public abstract void tearDown(); + + public static JsonNode getJSON(String jsonFile) { + ClassLoader classLoader = ModelTest.class.getClassLoader(); + String fileName; + try { + fileName = classLoader.getResource(jsonFile).getFile(); + ObjectMapper mapper = new ObjectMapper(); + return mapper.readTree(new File(fileName)); + } catch (IOException e) { + e.printStackTrace(); + } + + return null; + } + + public boolean compareLists(List list, String json, String key) { + try { + JsonNode jsonArray = new ObjectMapper().readTree(json).get(key); + if (jsonArray.isArray()) { + for (JsonNode objNode : jsonArray) { + boolean eq = false; + for (T item : list) { + if (objNode.asText().equals(item.toString())) { + eq = true; + break; + } + } + if (!eq) { + return false; + } + } + } + } catch (IOException e) { + e.printStackTrace(); + return false; + } + return true; + } + + public List getLinksHref(String json, String key) { + List vals = null; + + try { + vals = new ArrayList<>(); + + JsonNode jsonArray = new ObjectMapper().readTree(json).get(key); + if (jsonArray.isArray()) { + for (final JsonNode objNode : jsonArray) { + vals.add(objNode.get("href").textValue()); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + return vals; + } +} diff --git a/src/test/bookingbugAPI/models/NoteTest.java b/src/test/bookingbugAPI2/models/NoteTest.java similarity index 89% rename from src/test/bookingbugAPI/models/NoteTest.java rename to src/test/bookingbugAPI2/models/NoteTest.java index 8d3faa5..93e021d 100644 --- a/src/test/bookingbugAPI/models/NoteTest.java +++ b/src/test/bookingbugAPI2/models/NoteTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/ParamsTest.java b/src/test/bookingbugAPI2/models/ParamsTest.java similarity index 90% rename from src/test/bookingbugAPI/models/ParamsTest.java rename to src/test/bookingbugAPI2/models/ParamsTest.java index f99f54f..c260309 100644 --- a/src/test/bookingbugAPI/models/ParamsTest.java +++ b/src/test/bookingbugAPI2/models/ParamsTest.java @@ -1,11 +1,9 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; -import bookingbugAPI.models.params.BookingCreateParams; -import bookingbugAPI.models.params.ClientCreateParams; -import com.fasterxml.jackson.databind.ObjectMapper; +import bookingbugAPI2.models.params.BookingCreateParams; +import bookingbugAPI2.models.params.ClientCreateParams; import org.junit.Test; -import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; diff --git a/src/test/bookingbugAPI/models/PeopleTest.java b/src/test/bookingbugAPI2/models/PersonTest.java similarity index 92% rename from src/test/bookingbugAPI/models/PeopleTest.java rename to src/test/bookingbugAPI2/models/PersonTest.java index 0badc3f..dee0948 100644 --- a/src/test/bookingbugAPI/models/PeopleTest.java +++ b/src/test/bookingbugAPI2/models/PersonTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -11,7 +11,7 @@ import static org.junit.Assert.assertTrue; -public class PeopleTest extends ModelTest { +public class PersonTest extends ModelTest { private JsonNode jsonNode; @Override @@ -23,7 +23,7 @@ public void setUp() { @Override @Test public void modelInit() throws ParseException { - People person = new People(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); + Person person = new Person(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); JsonNode jsonLinks = jsonNode.get("_links"); assertTrue(person.getId().equals(jsonNode.get("id").intValue())); diff --git a/src/test/bookingbugAPI/models/QuestionTest.java b/src/test/bookingbugAPI2/models/QuestionTest.java similarity index 95% rename from src/test/bookingbugAPI/models/QuestionTest.java rename to src/test/bookingbugAPI2/models/QuestionTest.java index 03c8b03..11c3785 100644 --- a/src/test/bookingbugAPI/models/QuestionTest.java +++ b/src/test/bookingbugAPI2/models/QuestionTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/models/ResourceTest.java b/src/test/bookingbugAPI2/models/ResourceTest.java similarity index 94% rename from src/test/bookingbugAPI/models/ResourceTest.java rename to src/test/bookingbugAPI2/models/ResourceTest.java index b9935fa..2ba2ed5 100644 --- a/src/test/bookingbugAPI/models/ResourceTest.java +++ b/src/test/bookingbugAPI2/models/ResourceTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI2/models/ScheduleTest.java b/src/test/bookingbugAPI2/models/ScheduleTest.java new file mode 100644 index 0000000..5f8c2f6 --- /dev/null +++ b/src/test/bookingbugAPI2/models/ScheduleTest.java @@ -0,0 +1,39 @@ +package bookingbugAPI2.models; + +import com.fasterxml.jackson.databind.JsonNode; +import helpers2.HttpServiceResponse; +import helpers2.Utils; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import java.text.ParseException; + +import static org.junit.Assert.assertTrue; + + +public class ScheduleTest extends MemberTest { + private JsonNode jsonNode; + + @Override + @Before + public void setUp() { + jsonNode = getJSON("json/schedule.json"); + } + + @Override + @Test + public void modelInit() throws ParseException { + Schedule schedule = new Schedule(new HttpServiceResponse(Utils.stringToContentRep(jsonNode.toString()))); + + assertTrue(schedule.getName().equals(jsonNode.get("name").textValue())); + assertTrue(schedule.getDesc().equals(jsonNode.get("desc").textValue())); + assertTrue(schedule.getStyle().equals(jsonNode.get("style").intValue())); + } + + @Override + @After + public void tearDown() { + jsonNode = null; + } +} diff --git a/src/test/bookingbugAPI/models/ServiceTest.java b/src/test/bookingbugAPI2/models/ServiceTest.java similarity index 97% rename from src/test/bookingbugAPI/models/ServiceTest.java rename to src/test/bookingbugAPI2/models/ServiceTest.java index 5df3c0d..1ddb97c 100644 --- a/src/test/bookingbugAPI/models/ServiceTest.java +++ b/src/test/bookingbugAPI2/models/ServiceTest.java @@ -1,8 +1,8 @@ -package bookingbugAPI.models; +package bookingbugAPI2.models; import com.fasterxml.jackson.databind.JsonNode; -import helpers.HttpServiceResponse; -import helpers.Utils; +import helpers2.HttpServiceResponse; +import helpers2.Utils; import org.junit.After; import org.junit.Before; import org.junit.Test; diff --git a/src/test/bookingbugAPI/services/HalCustomJsonDeserializer.java b/src/test/bookingbugAPI2/services/HalCustomJsonDeserializer.java similarity index 91% rename from src/test/bookingbugAPI/services/HalCustomJsonDeserializer.java rename to src/test/bookingbugAPI2/services/HalCustomJsonDeserializer.java index 6d01400..67607c1 100644 --- a/src/test/bookingbugAPI/services/HalCustomJsonDeserializer.java +++ b/src/test/bookingbugAPI2/services/HalCustomJsonDeserializer.java @@ -1,14 +1,13 @@ -package bookingbugAPI.services; +package bookingbugAPI2.services; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; -import helpers.hal_addon.CustomJsonDeserializer; +import helpers2.hal_addon.CustomJsonDeserializer; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; -import java.util.HashMap; import java.util.Map; import static org.junit.Assert.assertTrue; diff --git a/src/test/bookingbugAPI/services/OkHttpServiceTest.java b/src/test/bookingbugAPI2/services/OkHttpServiceTest.java similarity index 89% rename from src/test/bookingbugAPI/services/OkHttpServiceTest.java rename to src/test/bookingbugAPI2/services/OkHttpServiceTest.java index 485d03c..fa7c0b2 100644 --- a/src/test/bookingbugAPI/services/OkHttpServiceTest.java +++ b/src/test/bookingbugAPI2/services/OkHttpServiceTest.java @@ -1,12 +1,15 @@ -package bookingbugAPI.services; +package bookingbugAPI2.services; -import bookingbugAPI.api.AbstractAPI; -import bookingbugAPI.models.HttpException; +import bookingbugAPI2.api.AbstractAPI; +import bookingbugAPI2.models.HttpException; +import bookingbugAPI2.services.cache.MockCacheService; +import bookingbugAPI2.services.http.OkHttpService; +import bookingbugAPI2.services.http.PlainHttpService; import com.squareup.okhttp.mockwebserver.Dispatcher; import com.squareup.okhttp.mockwebserver.MockResponse; import com.squareup.okhttp.mockwebserver.MockWebServer; import com.squareup.okhttp.mockwebserver.RecordedRequest; -import helpers.HttpServiceResponse; +import helpers2.HttpServiceResponse; import org.junit.Test; import java.io.IOException; @@ -64,7 +67,7 @@ public MockResponse dispatch(RecordedRequest request) throws InterruptedExceptio private AbstractAPI.ApiConfig getConfig() { AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig(); - config.withApp(appId, appKey).withCache(CacheService.MOCK()); + config.withApp(appId, appKey).withCacheService(new MockCacheService()); return config; } @@ -85,7 +88,7 @@ private HttpException tryGet(OkHttpService httpService, URL url) { */ @Test public void headerTest() throws IOException { - AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withNothing().withCache(CacheService.MOCK()); + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withNothing().withCacheService(new MockCacheService()); OkHttpService httpService = new OkHttpService(config); MockWebServer server = new MockWebServer(); @@ -125,7 +128,7 @@ public void headerTest() throws IOException { */ @Test public void testPOST() throws IOException { - AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCache(CacheService.MOCK()); + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCacheService(new MockCacheService()); OkHttpService httpService = new OkHttpService(config); MockWebServer server = new MockWebServer(); @@ -141,7 +144,7 @@ public void testPOST() throws IOException { try { //With specific encoding - response = httpService.api_POST(postURL, HttpService.urlEncodedContentType, params); + response = httpService.api_POST(postURL, PlainHttpService.urlEncodedContentType, params); assertEquals("Received status should be 201", response.getRep().getContent(), "{\"status\":\"201\"}"); //With default encoding @@ -160,7 +163,7 @@ public void testPOST() throws IOException { */ @Test public void testPUT() throws IOException { - AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCache(CacheService.MOCK()); + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCacheService(new MockCacheService()); OkHttpService httpService = new OkHttpService(config); MockWebServer server = new MockWebServer(); @@ -176,7 +179,7 @@ public void testPUT() throws IOException { try { //With specific encoding - response = httpService.api_PUT(putURL, HttpService.urlEncodedContentType, params); + response = httpService.api_PUT(putURL, PlainHttpService.urlEncodedContentType, params); assertEquals("Received status should be 201", response.getRep().getContent(), "{\"status\":\"updated\"}"); //With default encoding @@ -195,7 +198,7 @@ public void testPUT() throws IOException { */ @Test public void testDELETE() throws IOException { - AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCache(CacheService.MOCK()); + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig().withCacheService(new MockCacheService()); OkHttpService httpService = new OkHttpService(config); MockWebServer server = new MockWebServer(); @@ -215,7 +218,7 @@ public void testDELETE() throws IOException { assertEquals("Received status should be 200", response.getRep().getContent(), "{\"status\":\"deleted\"}"); //With specific encoding - response = httpService.api_DELETE(deleteURL, HttpService.urlEncodedContentType, params); + response = httpService.api_DELETE(deleteURL, PlainHttpService.urlEncodedContentType, params); assertEquals("Received status should be 201", response.getRep().getContent(), "{\"status\":\"deleted\"}"); //With default encoding diff --git a/src/test/bookingbugAPI/services/HttpServiceTest.java b/src/test/bookingbugAPI2/services/PlainHttpServiceTest.java similarity index 78% rename from src/test/bookingbugAPI/services/HttpServiceTest.java rename to src/test/bookingbugAPI2/services/PlainHttpServiceTest.java index f711735..ad28ad5 100644 --- a/src/test/bookingbugAPI/services/HttpServiceTest.java +++ b/src/test/bookingbugAPI2/services/PlainHttpServiceTest.java @@ -1,7 +1,8 @@ -package bookingbugAPI.services; +package bookingbugAPI2.services; -import bookingbugAPI.api.PublicURLS; -import bookingbugAPI.models.HttpException; +import bookingbugAPI2.api.PublicURLS; +import bookingbugAPI2.models.HttpException; +import bookingbugAPI2.services.http.PlainHttpService; import org.junit.*; import java.net.MalformedURLException; @@ -13,7 +14,7 @@ /** * Testing that the urls are available and receiving requests (the response is not relevant). */ -public class HttpServiceTest { +public class PlainHttpServiceTest { private static final int CompanyId = 10; @@ -22,7 +23,7 @@ public class HttpServiceTest { public void companyDetails(){ try { URL url = new URL(PublicURLS.Details.companyDetails().set("companyId", CompanyId).expand()); - assertNotNull(HttpService.api_GET(url, true)); + assertNotNull(PlainHttpService.api_GET(url, true)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (HttpException e) { @@ -35,7 +36,7 @@ public void companyDetails(){ public void eventGroupList(){ try { URL url = new URL(PublicURLS.EventGroup.eventGroupList().set("companyId", CompanyId).expand()); - assertNotNull(HttpService.api_GET(url, true)); + assertNotNull(PlainHttpService.api_GET(url, true)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (HttpException e) { @@ -48,7 +49,7 @@ public void eventGroupList(){ public void eventList(){ try { URL url = new URL(PublicURLS.Event.eventList().set("companyId", CompanyId).expand()); - assertNotNull(HttpService.api_GET(url, true)); + assertNotNull(PlainHttpService.api_GET(url, true)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (HttpException e) { @@ -61,7 +62,7 @@ public void eventList(){ public void eventRead(){ try { URL url = new URL(PublicURLS.Event.eventRead().set("companyId", CompanyId).expand()); - assertNotNull(HttpService.api_GET(url, true)); + assertNotNull(PlainHttpService.api_GET(url, true)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (HttpException e) { @@ -74,7 +75,7 @@ public void eventRead(){ public void eventChainList(){ try { URL url = new URL(PublicURLS.EventChain.eventChainList().set("companyId", CompanyId).expand()); - assertNotNull(HttpService.api_GET(url, true)); + assertNotNull(PlainHttpService.api_GET(url, true)); } catch (MalformedURLException e) { e.printStackTrace(); } catch (HttpException e) { diff --git a/src/test/bookingbugAPI2/services/SQLiteCacheServiceTest.java b/src/test/bookingbugAPI2/services/SQLiteCacheServiceTest.java new file mode 100644 index 0000000..6887212 --- /dev/null +++ b/src/test/bookingbugAPI2/services/SQLiteCacheServiceTest.java @@ -0,0 +1,141 @@ +package bookingbugAPI2.services; + +import bookingbugAPI2.api.AbstractAPI; +import com.squareup.okhttp.mockwebserver.Dispatcher; +import com.squareup.okhttp.mockwebserver.MockResponse; +import com.squareup.okhttp.mockwebserver.MockWebServer; +import com.squareup.okhttp.mockwebserver.RecordedRequest; +import helpers2.HttpServiceResponse; +import org.junit.Test; + +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.Objects; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Created by sebi on 17.08.2016. + */ +public class SQLiteCacheServiceTest { + + final Dispatcher dispatcher = new Dispatcher() { + + @Override + public MockResponse dispatch(RecordedRequest request) throws InterruptedException { + + //Check post data + if(request.getPath().equals("/post/") && Objects.equals(request.getMethod(), "POST") && request.getBodySize() != 0) { + return new MockResponse().setResponseCode(201).setBody("{\"status\":\"201\"}"); + } + + //Check put data + if(request.getPath().equals("/put/") && Objects.equals(request.getMethod(), "PUT") && request.getBodySize() != 0) { + return new MockResponse().setResponseCode(201).setBody("{\"status\":\"updated\"}"); + } + + //Check delete data + if(request.getPath().equals("/delete/") && Objects.equals(request.getMethod(), "DELETE")) { + return new MockResponse().setResponseCode(201).setBody("{\"status\":\"deleted\"}"); + } + + return new MockResponse().setResponseCode(200).setBody("{}"); + } + }; + + @Test + public void testExpiry() throws InterruptedException { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig(); + config.cacheService().setExpiryDurationSec(1); + String dummyURL = "dummy_url"; + String dummyResp = "{\"dummy\":\"dummy\"}"; + String dummyTag = "MY_TAG"; + + config.cacheService().invalidateResultsByTag(dummyTag); + config.cacheService().storeResult(dummyURL, "GET", dummyResp, dummyTag); + + Thread.sleep(500); + assertNotNull(config.cacheService().getDBResponse(dummyURL, "GET")); + + Thread.sleep(600); + assertNull(config.cacheService().getDBResponse(dummyURL, "GET")); + } + + @Test + public void testCacheGET() throws IOException { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig(); + + MockWebServer server = new MockWebServer(); + server.setDispatcher(dispatcher); + server.start(); + + URL dummyGET = server.url("/get/").url(); + String dummyTag = "MY_TAG"; + + config.cacheService().invalidateResultsByTag(dummyTag); + HttpServiceResponse response = config.httpService().api_GET(dummyGET, dummyTag); + assertNotNull(response); + assertNotNull(config.cacheService().getDBResponse(dummyGET.toString(), "GET")); + server.shutdown(); + } + + private void testInvalidationOnVerb(String method) throws IOException { + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig(); + + MockWebServer server = new MockWebServer(); + server.setDispatcher(dispatcher); + server.start(); + + URL dummyGET1 = server.url("/get/").url(); + URL dummyGET2 = server.url("/get2/").url(); + URL dummyPOST = server.url("/post/").url(); + String dummyTag1 = "MY_TAG1"; + String dummyTag2 = "MY_TAG2"; + HttpServiceResponse response = null; + + config.cacheService().invalidateResultsByTag(dummyTag1); + config.cacheService().invalidateResultsByTag(dummyTag2); + + //Trigger get to cache + response = config.httpService().api_GET(dummyGET1, dummyTag1); + response = config.httpService().api_GET(dummyGET2, dummyTag2); + assertNotNull(response); + assertNotNull(config.cacheService().getDBResponse(dummyGET1.toString(), "GET")); + + //Post with tag1 and check cache for tag1 and tag2 + switch (method) { + case "POST": + response = config.httpService().api_POST(dummyPOST, new HashMap(), dummyTag1); + break; + case "PUT": + response = config.httpService().api_PUT(dummyPOST, new HashMap(), dummyTag1); + break; + case "DELETE": + response = config.httpService().api_DELETE(dummyPOST, new HashMap(), dummyTag1); + break; + default: response = null; + } + + assertNotNull(response); + assertNull(config.cacheService().getDBResponse(dummyGET1.toString(), "GET")); + assertNotNull(config.cacheService().getDBResponse(dummyGET2.toString(), "GET")); + server.shutdown(); + } + + @Test + public void testInvalidationOnPOST() throws IOException { + testInvalidationOnVerb("POST"); + } + + @Test + public void testInvalidationOnPUT() throws IOException { + testInvalidationOnVerb("PUT"); + } + + @Test + public void testInvalidationOnDELETE() throws IOException { + testInvalidationOnVerb("DELETE"); + } +} diff --git a/src/test/bookingbugAPI/services/UrlEncoderTest.java b/src/test/bookingbugAPI2/services/UrlEncoderTest.java similarity index 97% rename from src/test/bookingbugAPI/services/UrlEncoderTest.java rename to src/test/bookingbugAPI2/services/UrlEncoderTest.java index 34ba573..8c88b9a 100644 --- a/src/test/bookingbugAPI/services/UrlEncoderTest.java +++ b/src/test/bookingbugAPI2/services/UrlEncoderTest.java @@ -1,7 +1,7 @@ -package bookingbugAPI.services; +package bookingbugAPI2.services; import com.fasterxml.jackson.databind.ObjectMapper; -import helpers.Http; +import helpers2.Http; import org.junit.Test; import java.io.IOException; diff --git a/src/test/helpers/TokenGeneratorTest.java b/src/test/helpers/TokenGeneratorTest.java deleted file mode 100644 index 8ae92c4..0000000 --- a/src/test/helpers/TokenGeneratorTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package helpers; - -import bookingbugAPI.services.HttpService; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ObjectNode; -import org.junit.Test; - -import java.net.URL; - -import static org.junit.Assert.assertNotNull; - -/** - * Testing that the urls are available and receiving requests (the response is not relevant). - */ -public class TokenGeneratorTest { - - private static final String CompanyId = "37023"; - - @Test - public void companyDetails(){ - try { - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.createObjectNode(); - - ((ObjectNode)jsonNode).put("first_name", "John"); - ((ObjectNode)jsonNode).put("last_name", "Smith"); - ((ObjectNode)jsonNode).put("email", "cornel+test@assist.ro"); - ((ObjectNode)jsonNode).put("mobile", "0123456789"); - - String token = TokenGenerator.getInstance(CompanyId, "abc").create(jsonNode); - - String urlStr = new Config().serverUrl + "/login/sso/" + CompanyId + "?token=" + token; - //String urlStr = "https://eu1.bookingbug.com/api/v1/login/sso/37000?token=" + token; - //String urlStr = "https://eu1.bookingbug.com/api/v1/login/sso/36990?token=" + token; - //String urlStr = "http://192.168.100.123:3000/api/v1/login/sso/37021?token=" + token + ""; - - URL url = new URL(urlStr); - assertNotNull(HttpService.api_POST(url, true)); - - } catch (Exception e) { - e.printStackTrace(); - } - } - -} \ No newline at end of file diff --git a/src/test/helpers2/TokenGeneratorTest.java b/src/test/helpers2/TokenGeneratorTest.java new file mode 100644 index 0000000..589f2e0 --- /dev/null +++ b/src/test/helpers2/TokenGeneratorTest.java @@ -0,0 +1,51 @@ +package helpers2; + +import bookingbugAPI2.api.AbstractAPI; +import bookingbugAPI2.api.AdminURLS; +import bookingbugAPI2.services.cache.MockCacheService; +import bookingbugAPI2.services.http.PlainHttpService; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.Test; + +import java.net.URL; +import java.util.HashMap; + +import static org.junit.Assert.assertNotNull; + +/** + * Testing that the urls are available and receiving requests (the response is not relevant). + */ +public class TokenGeneratorTest { + + private static final String companyId = "37048"; + //private static final String companyId = "37023"; + + @Test + public void companyDetails(){ + try { + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.createObjectNode(); + + ((ObjectNode)jsonNode).put("first_name", "John2"); + ((ObjectNode)jsonNode).put("last_name", "Smith"); + ((ObjectNode)jsonNode).put("email", "sefu@bookingbug.com"); + ((ObjectNode)jsonNode).put("mobile", "0123466789"); + + String token = TokenGenerator.getInstance(companyId, "abcd").create(jsonNode); + + AbstractAPI.ApiConfig config = new AbstractAPI.ApiConfig() + .withCacheService(new MockCacheService()) + .withAuthToken(token); + + String loginUrl = new AdminURLS(config).login().sso().set("companyId", companyId).set("token", token).expand(); + HttpServiceResponse response = config.httpService().api_POST(new URL(loginUrl), new HashMap<>()); + assertNotNull(response); + + } catch (Exception e) { + e.printStackTrace(); + } + } + +} \ No newline at end of file diff --git a/src/test/resources/json/clinic.json b/src/test/resources/json/clinic.json new file mode 100644 index 0000000..1043b21 --- /dev/null +++ b/src/test/resources/json/clinic.json @@ -0,0 +1,19 @@ +{ + "name": "string", + "start_time": "2016-07-11T12:30:32.596Z", + "end_time": "2016-07-11T12:30:32.596Z", + "resource_ids": [ + "string" + ], + "person_ids": [ + "string" + ], + "service_ids": [ + "string" + ], + "repeat_rule": { + "id": 0, + "rules": {}, + "properties": {} + } +} \ No newline at end of file diff --git a/src/test/resources/json/multiple_login.json b/src/test/resources/json/multiple_login.json new file mode 100644 index 0000000..76ee337 --- /dev/null +++ b/src/test/resources/json/multiple_login.json @@ -0,0 +1,77 @@ +{ + "email": "sebii@assist.ro", + "path": "https://assist-dev03.bookingbug.com/api/v1", + "_embedded": { + "members": [], + "administrators": [ + { + "name": "Sebi Macarescu", + "email": "sebii@assist.ro", + "role": "admin", + "company_id": 37047, + "company_name": "Sebi Company 1", + "_links": { + "self": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59" + }, + "edit": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59/edit" + }, + "company": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/company" + }, + "login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin/37047" + }, + "base_login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin" + } + } + }, + { + "name": "Sebi Macarescu", + "email": "sebii@assist.ro", + "role": "admin", + "company_id": 37048, + "company_name": "Sebi Company 2", + "_links": { + "self": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37048/administrators/63" + }, + "edit": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37048/administrators/63/edit" + }, + "company": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37048/company" + }, + "login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin/37048" + }, + "base_login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin" + } + } + } + ] + }, + "_links": { + "self": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login" + }, + "members": [], + "administrators": [ + { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59", + "templated": true + }, + { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37048/administrators/63", + "templated": true + }, + { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin//user/30", + "templated": true + } + ] + } +} \ No newline at end of file diff --git a/src/test/resources/json/myadmin.json b/src/test/resources/json/myadmin.json new file mode 100644 index 0000000..e69de29 diff --git a/src/test/resources/json/purchase.json b/src/test/resources/json/purchase.json new file mode 100644 index 0000000..6584732 --- /dev/null +++ b/src/test/resources/json/purchase.json @@ -0,0 +1,244 @@ +{ + "total_price": 1000, + "price": 1000, + "paid": 0, + "deposit": 0, + "tax_payable_on_price": 0, + "tax_payable_on_deposit": 0, + "tax_payable_on_due_now": 0, + "due_now": 1000, + "long_id": "PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D", + "id": 9512395, + "client_name": "Et Sdfg", + "created_at": "2016-06-20T16:18:01Z", + "certificate_paid": 0, + "payment_type": "other", + "_embedded": { + "client": { + "first_name": "et", + "last_name": "sdfg", + "email": "sdfg@sdf.com", + "country": "United Kingdom", + "phone_prefix": "44", + "mobile_prefix": "44", + "id": 2746138, + "answers": [], + "deleted": false, + "notifications": {}, + "client_type": "Contact", + "_links": { + "self": { + "href": "https://uk.bookingbug.com/api/v1/49511/client/2746138" + }, + "questions": { + "href": "https://uk.bookingbug.com/api/v1/49511/client_details" + } + } + }, + "member": { + "id": 2746138, + "name": "Et Sdfg", + "first_name": "et", + "last_name": "sdfg", + "client_type": "Contact", + "email": "sdfg@sdf.com", + "country": "United Kingdom", + "phone_prefix": "44", + "mobile_prefix": "44", + "path": "https://uk.bookingbug.com/api/v1", + "company_id": 49511, + "has_active_wallet": false, + "has_wallet": false, + "_links": { + "self": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138{?embed}", + "templated": true + }, + "bookings": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138/bookings{?start_date,end_date,include_cancelled,page,per_page}", + "templated": true + }, + "pre_paid_bookings": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138/pre_paid_bookings{?include_invalid,event_id}", + "templated": true + }, + "purchase_totals": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138/purchase_totals{?start_date,end_date,page,per_page}", + "templated": true + }, + "edit_member": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138/edit" + }, + "company": { + "href": "https://uk.bookingbug.com/api/v1/company/49511" + }, + "update_password": { + "href": "https://uk.bookingbug.com/api/v1/login/49511/update_password/2746138" + }, + "send_welcome_email": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138/send_welcome_email" + } + } + }, + "bookings": [{ + "id": 10977829, + "full_describe": "My Recurring Event", + "describe": "Tue 21st Jun 10:00am, 2 hours", + "datetime": "2016-06-21T10:00:00+01:00", + "end_datetime": "2016-06-21T12:00:00+01:00", + "duration": 120, + "duration_span": 7200, + "listed_duration": 120, + "on_waitlist": false, + "company_id": 49511, + "attended": true, + "price": 1000, + "due_now": 1000, + "paid": 0, + "quantity": 1, + "event_id": 1050864, + "session_id": 225004, + "service_id": 102277, + "purchase_id": 9512395, + "purchase_ref": "PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D", + "settings": {}, + "min_cancellation_time": "2016-06-19T09:00:00+01:00", + "service_name": "Group", + "time_zone": "Europe/London", + "address": { + "id": 50926, + "address1": "1 drury lane", + "address2": "mufin maker street", + "address3": "bakers ville", + "address4": "love town", + "address5": "bristol", + "postcode": "tn22 8pz", + "country": "United Kingdom", + "lat": 50.972873, + "long": 0.0966977, + "map_url": "", + "map_marker": "1+drury+lane,+mufin+maker+street,+bakers+ville,+love+town,+bristol,+tn22+8pz,+United+Kingdom", + "phone": "+376 775506660", + "homephone": "775506660", + "_links": { + "self": { + "href": "https://uk.bookingbug.com/api/v1/49511/addresses/50926" + } + } + }, + "booking_type": "Booking", + "slot_id": 14171479, + "first_name": "et", + "last_name": "sdfg", + "email": "sdfg@sdf.com", + "_embedded": { + "answers": [], + "survey_answers": [] + }, + "_links": { + "self": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/bookings/10977829" + }, + "check_in": { + "href": "https://uk.bookingbug.com/api/v1/bookings/10977829/check_in" + }, + "attachments": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/bookings/10977829/attach" + }, + "service": { + "href": "https://uk.bookingbug.com/api/v1/49511/services/102277" + }, + "company": { + "href": "https://uk.bookingbug.com/api/v1/company/49511" + }, + "client": { + "href": "https://uk.bookingbug.com/api/v1/49511/client/2746138" + }, + "member": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138{?embed}", + "templated": true + }, + "event_groups": { + "href": "https://uk.bookingbug.com/api/v1/49511/event_groups/225004", + "templated": true, + "title": "Group" + }, + "event_chain": { + "title": "My Recurring Event", + "href": "https://uk.bookingbug.com/api/v1/49511/event_chains/225004{?member_level_id}", + "templated": true + }, + "survey_questions": { + "href": "https://uk.bookingbug.com/api/v1/49511/31503/survey_questions{?admin_only}", + "templated": true + }, + "address": { + "href": "https://uk.bookingbug.com/api/v1/49511/addresses/50926" + } + } + }], + "packages": [], + "products": [], + "pre_paid_bookings": [], + "deals": [], + "course_bookings": [], + "external_purchases": [], + "confirm_messages": [] + }, + "_links": { + "self": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D" + }, + "ical": { + "href": "http://uk.bookingbug.com/ical/total/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D" + }, + "web_cal": { + "href": "webcal://uk.bookingbug.com/ical/total/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D" + }, + "gcal": { + "href": "http://www.google.com/calendar/event?dates=20160621T090000Z%2F20160621T110000Z&details=&sprop=www.bookingbug.com&text=Booking%3A+My+Recurring+Event+at+Phones&trp=false&action=TEMPLATE" + }, + "client": { + "href": "https://uk.bookingbug.com/api/v1/49511/client/2746138" + }, + "member": { + "href": "https://uk.bookingbug.com/api/v1/49511/members/2746138{?embed}", + "templated": true + }, + "company": { + "href": "https://uk.bookingbug.com/api/v1/company/49511" + }, + "bookings": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/bookings" + }, + "packages": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/packages" + }, + "pre_paid_bookings": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/pre_paid_bookings" + }, + "products": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/products" + }, + "deals": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/deals" + }, + "confirm_messages": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/confirm_messages" + }, + "book_waitlist_item": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/book_waitlist_item" + }, + "external_purchases": { + "href": "https://uk.bookingbug.com/api/v1/purchases/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D/external_purchases" + }, + "print": { + "href": "/angular/print_purchase.html?id=PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D&company_id=49511" + }, + "paypal_express": { + "href": "/pay/paypal_express/PS78SXbSy8Edp-5GOTUxMjM5NQ%3D%3D{?landing_page,allow_guest_checkout,allow_note,logo_image,max_amount,no_shipping,allowed_payment_method}", + "templated": true, + "type": "location" + } + } +} \ No newline at end of file diff --git a/src/test/resources/json/resource.json b/src/test/resources/json/resource.json index 42cd2be..a6788f3 100644 --- a/src/test/resources/json/resource.json +++ b/src/test/resources/json/resource.json @@ -1,21 +1,33 @@ { - "id": 23352, - "name": "Consultation Room 1", + "id": 5, + "name": "My Resource 2", + "description": "This is Spartaaaa !", "type": "resource", "deleted": false, "disabled": false, - "company_id": 37901, - "email": "conor+email1@bookingbug.com,conor+email2@bookingbug.com", - "order": 23352, + "company_id": 36990, + "email": "andrei.robu@assist.ro", + "order": 5, "_links": { "self": { - "href": "https://uk.bookingbug.com/api/v1/37901/resources/23352" + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/resources/5" }, "items": { - "href": "https://uk.bookingbug.com/api/v1/37901/items?resource_id=23352" + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/items?resource_id=5" }, "address": { - "href": "https://uk.bookingbug.com/api/v1/37901/addresses/41821" + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/addresses/30192" + }, + "edit": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/resources/5/edit" + }, + "block": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/resources/5/block" + }, + "schedule": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/36990/schedules/48315{?start_date,end_date}", + "templated": true } - } -} + }, + "schedule_id": 48315 +} \ No newline at end of file diff --git a/src/test/resources/json/schedule.json b/src/test/resources/json/schedule.json new file mode 100644 index 0000000..2d1248e --- /dev/null +++ b/src/test/resources/json/schedule.json @@ -0,0 +1,6 @@ +{ + "rules": {}, + "name": "string", + "desc": "string", + "style": 0 +} \ No newline at end of file diff --git a/src/test/resources/json/service.json b/src/test/resources/json/service.json index d8ba9ce..e84496a 100644 --- a/src/test/resources/json/service.json +++ b/src/test/resources/json/service.json @@ -56,6 +56,9 @@ }, "all_children": { "href": "https://uk.bookingbug.com/api/v1/37901/services/55600/all_children" + }, + "edit": { + "href": "https://uk.bookingbug.com/api/v1/admin/37901/services/55600/edit" } } } diff --git a/src/test/resources/json/simple_login.json b/src/test/resources/json/simple_login.json new file mode 100644 index 0000000..2812050 --- /dev/null +++ b/src/test/resources/json/simple_login.json @@ -0,0 +1,45 @@ +{ + "email": "sebii@assist.ro", + "auth_token": "9F6UCEWzP67taH9ddCdLbw", + "company_id": 37047, + "path": "https://assist-dev03.bookingbug.com/api/v1", + "role": "admin", + "_embedded": { + "members": [], + "administrators": [ + { + "name": "Sebi Macarescu", + "email": "sebii@assist.ro", + "role": "admin", + "company_id": 37047, + "company_name": "Sebi Company 1", + "_links": { + "self": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59" + }, + "edit": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59/edit" + }, + "company": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/company" + }, + "login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin/37047" + }, + "base_login": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/admin" + } + } + } + ] + }, + "_links": { + "self": { + "href": "https://assist-dev03.bookingbug.com/api/v1/login/37047" + }, + "administrator": { + "href": "https://assist-dev03.bookingbug.com/api/v1/admin/37047/administrators/59", + "templated": true + } + } +} \ No newline at end of file diff --git a/src/test/resources/json/slot.json b/src/test/resources/json/slot.json new file mode 100644 index 0000000..5cf2701 --- /dev/null +++ b/src/test/resources/json/slot.json @@ -0,0 +1,7 @@ +{ + "start_time": "string", + "end_time": "string", + "allday": "string", + "person_id": "string", + "resource_id": "string" +} \ No newline at end of file