package com.casamind.adware.server.servlet.rpc;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import com.casamind.adware.client.service.DataService;
import com.casamind.adware.server.domain.Company;
import com.casamind.adware.server.domain.Product;
import com.casamind.adware.server.domain.Publisher;
import com.casamind.adware.server.domain.Resource;
import com.casamind.adware.server.domain.Slot;
import com.casamind.adware.server.domain.UserAccount;
import com.casamind.adware.server.proxy.DatastoreProxy;
import com.casamind.adware.server.proxy.GDataDocumentsProxy;
import com.casamind.adware.server.utils.ServletHelper;
import com.casamind.adware.shared.AccessLevels;
import com.casamind.adware.shared.GoogleCalendarTaskTypes;
import com.casamind.adware.shared.GoogleDocumentsTaskTypes;
import com.casamind.adware.shared.ReportTypes;
import com.casamind.adware.shared.SlotStatus;
import com.casamind.adware.shared.model.CompanyDTO;
import com.casamind.adware.shared.model.CompanySummaryDTO;
import com.casamind.adware.shared.model.EntitySummary;
import com.casamind.adware.shared.model.GroupDTO;
import com.casamind.adware.shared.model.ProductDTO;
import com.casamind.adware.shared.model.ProductSummaryDTO;
import com.casamind.adware.shared.model.PublisherDTO;
import com.casamind.adware.shared.model.PublisherSummaryDTO;
import com.casamind.adware.shared.model.ResourceDTO;
import com.casamind.adware.shared.model.ResourceSummaryDTO;
import com.casamind.adware.shared.model.SlotDTO;
import com.casamind.adware.shared.model.SlotSummaryDTO;
import com.casamind.adware.shared.model.UserAccountDTO;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
@SuppressWarnings("serial")
public class DataServiceImpl extends RemoteServiceServlet implements
DataService {
private String gdataWebLogin, gdataWebPassword, gdataAdminLogin,
documentsFeedUrl, spreadsheetFeedUrl, gdataAdminPassword,
adminSpreadsheet, advertizingSlotsFrameURL,
readonlyCalendarFrameURL;
private GDataDocumentsProxy gdataProxy;
private long gdataThreadSleep;
private long gdataConnectTimeout;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = config.getServletContext();
gdataThreadSleep = Long.parseLong(context.getInitParameter("gdataThreadSleep"));
gdataConnectTimeout = Long.parseLong(context.getInitParameter("gdataConnectTimeout"));
gdataWebLogin = context.getInitParameter("gdataWebLogin");
gdataWebPassword = context.getInitParameter("gdataWebPassword");
gdataAdminLogin = context.getInitParameter("gdataAdminLogin");
gdataAdminPassword = context.getInitParameter("gdataAdminPassword");
adminSpreadsheet = context.getInitParameter("adminSpreadsheet");
documentsFeedUrl = context.getInitParameter("documentsFeedUrl");
spreadsheetFeedUrl = context.getInitParameter("spreadsheetFeedUrl");
advertizingSlotsFrameURL = context.getInitParameter("advertizingSlotsFrameURL");
readonlyCalendarFrameURL = context.getInitParameter("readonlyCalendarFrameURL");
}
@Override
public String getAdvertizingSlotsFrameURL() {
if (ServletHelper.isDevMode()) {
return "https://www.google.com/calendar/selfsched?sstoken=UUdFS1RwUkR5bDlWfGRlZmF1bHR8NTE1NTJjYTI1ODFhYzNhOTdmNjU3ODU2MWJiZjE5ZDE";
} else {
return advertizingSlotsFrameURL;
}
}
@Override
public String getReadonlyCalendarFrameURL() {
if (ServletHelper.isDevMode()) {
return "https://www.google.com/calendar/b/0/embed?showTitle=0&showCalendars=0&mode=WEEK&height=600&wkst=2&hl=fr&bgcolor=%23FFFFFF&src=avicena.dev%40gmail.com&color=%23060D5E&ctz=Africa%2FCasablanca";
} else {
return readonlyCalendarFrameURL;
}
}
@Override
public String getSpreadsheetURL(Long userId, String fileName) {
// if it's an administrator
if ((userId == null || userId == 0) && (fileName == null || "".equals(fileName))) {
gdataProxy = new GDataDocumentsProxy(documentsFeedUrl, spreadsheetFeedUrl, gdataAdminLogin, gdataAdminPassword, gdataThreadSleep, gdataConnectTimeout);
return gdataProxy.getSpreadsheetURL(adminSpreadsheet);
}
UserAccount user = DatastoreProxy.getUserAccountById(userId);
if (user != null) {
if (user.getGdataLogin() == null)
user.setGdataLogin(gdataWebLogin);
if (user.getGdataPassword() == null)
user.setGdataPassword(gdataWebPassword);
gdataProxy = new GDataDocumentsProxy(documentsFeedUrl, spreadsheetFeedUrl, user.getGdataLogin(), user.getGdataPassword(), gdataThreadSleep, gdataConnectTimeout);
DatastoreProxy.updateUser(user);
return gdataProxy.getSpreadsheetURL(fileName);
}
return null;
}
@Override
public String getBlobstoreUploadUrl(String currentURL) {
String url = BlobstoreServiceFactory.getBlobstoreService().createUploadUrl("/adware/uploadService");
;
if (ServletHelper.isDevMode()) {
url = url.replace("http://0.0.0.0:", "http://127.0.0.1:");
}
return url;
}
@Override
public Boolean deleteBlob(String key) {
try {
DatastoreProxy.deleteBlob(key);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public CompanyDTO getCompany(Long id) {
return Company.toDTO(DatastoreProxy.getCompanyById(id));
}
@Override
public CompanyDTO createCompany(CompanyDTO dto) {
Company entity = Company.toEntity(null, dto);
entity.setGdataLogin(gdataWebLogin);
entity.setGdataPassword(gdataWebPassword);
CompanyDTO returnedDTO = Company.toDTO((DatastoreProxy.createCompany(entity)));
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.CREATE).param("title", returnedDTO.getUUID()).param("folder", ReportTypes.COMPANY));
return returnedDTO;
}
@Override
public CompanyDTO updateCompany(CompanyDTO dto) {
return Company.toDTO((DatastoreProxy.updateCompany(dto)));
}
@Override
public Boolean deleteCompany(CompanyDTO dto) {
try {
DatastoreProxy.deleteCompany(dto.getId());
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.DELETE).param("title", dto.getUUID()));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public PublisherDTO getPublisher(Long id) {
return Publisher.toDTO(DatastoreProxy.getPublisherById(id));
}
@Override
public Boolean deletePublisher(PublisherDTO dto) {
try {
DatastoreProxy.deletePublisher(dto.getId());
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.DELETE).param("title", dto.getUUID()));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public PublisherDTO updatePublisher(PublisherDTO dto) {
return Publisher.toDTO((DatastoreProxy.updatePublisher(dto)));
}
@Override
public PublisherDTO createPublisher(PublisherDTO dto) {
Publisher entity = Publisher.toEntity(null, dto);
entity.setGdataLogin(gdataWebLogin);
entity.setGdataPassword(gdataWebPassword);
PublisherDTO returnedDTO = Publisher.toDTO((DatastoreProxy.createPublisher(entity)));
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.CREATE).param("title", returnedDTO.getUUID()).param("folder", ReportTypes.PUBLISHER));
return returnedDTO;
}
@Override
public ProductDTO getProduct(Long id) {
return Product.toDTO(DatastoreProxy.getProductById(id));
}
@Override
public Boolean deleteProduct(ProductDTO dto) {
try {
DatastoreProxy.deleteProduct(dto.getId());
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.DELETE).param("title", dto.getUUID()));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public ProductDTO updateProduct(ProductDTO dto) {
return Product.toDTO((DatastoreProxy.updateProduct(dto)));
}
@Override
public ProductDTO createProduct(ProductDTO dto) {
ProductDTO returnedDTO = Product.toDTO((DatastoreProxy.createProduct(Product.toEntity(null, dto))));
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/reports").param("task", GoogleDocumentsTaskTypes.CREATE).param("title", returnedDTO.getUUID()).param("folder", ReportTypes.PRODUCT));
return returnedDTO;
}
@Override
public List<ProductDTO> getProductsByPublisherId(Long id) {
List<ProductDTO> list = new ArrayList<ProductDTO>();
for (Product entity : DatastoreProxy.getProductsByPublisherId(id)) {
list.add(Product.toDTO(entity));
}
return list;
}
@Override
public ResourceDTO getResource(Long id) {
return Resource.toDTO(DatastoreProxy.getResourceById(id));
}
@Override
public Boolean deleteResource(ResourceSummaryDTO dto) {
try {
Resource resource = DatastoreProxy.getResourceById(dto.getId());
if (resource != null) {
BlobstoreServiceFactory.getBlobstoreService().delete(new BlobKey(resource.getBlobKey()));
DatastoreProxy.deleteResource(resource.getId());
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public Boolean deleteResource(ResourceDTO dto) {
try {
DatastoreProxy.deleteResource(dto.getId());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public ResourceDTO updateResource(ResourceDTO dto) {
return Resource.toDTO((DatastoreProxy.updateResource(dto)));
}
@Override
public ResourceDTO createResource(ResourceDTO dto) {
dto.setMimeType(DatastoreProxy.getMimeType(dto.getBlobKey()));
return Resource.toDTO((DatastoreProxy.createResource(Resource.toEntity(null, dto))));
}
@Override
public List<ResourceDTO> getResourcesByProductId(Long id) {
List<ResourceDTO> list = new ArrayList<ResourceDTO>();
for (Resource entity : DatastoreProxy.getResourcesByProductId(id)) {
list.add(Resource.toDTO(entity));
}
return list;
}
@Override
public List<ResourceSummaryDTO> getResourceSummariesByPublisherId(Long id) {
List<ResourceSummaryDTO> list = new ArrayList<ResourceSummaryDTO>();
for (Resource entity : DatastoreProxy.getResourcesByPublisherId(id)) {
list.add(Resource.toSummaryDTO(entity));
}
return list;
}
@Override
public List<ResourceSummaryDTO> getResourceSummariesByCompanyId(Long id) {
List<ResourceSummaryDTO> list = new ArrayList<ResourceSummaryDTO>();
for (Resource entity : DatastoreProxy.getResourcesByCompanyId(id)) {
list.add(Resource.toSummaryDTO(entity));
}
return list;
}
@Override
public List<EntitySummary> getEntitySummaries(UserAccountDTO user) {
List<EntitySummary> list = new ArrayList<EntitySummary>();
int accessLevel = user.getAccessLevel();
String login = user.getLogin();
if (accessLevel == AccessLevels.Publisher) {
Publisher publisher = DatastoreProxy.getPublisherByLogin(login);
if (publisher != null) {
for (Product entity : DatastoreProxy.getProductsByPublisherId(publisher.getId())) {
list.add(Product.toSummaryDTO(entity));
}
}
} else if (accessLevel == AccessLevels.Company) {
Company company = DatastoreProxy.getCompanyByLogin(login);
if (company != null) {
for (Publisher entity : DatastoreProxy.getPublishersByCompanyId(company.getId())) {
list.add(Publisher.toSummaryDTO(entity));
}
}
} else if (accessLevel == AccessLevels.Administrator) {
for (Company entity : DatastoreProxy.getCompanies()) {
list.add(Company.toSummaryDTO(entity));
}
}
return list;
}
@Override
public List<EntitySummary> getCompanies() {
List<EntitySummary> list = new ArrayList<EntitySummary>();
for (Company entity : DatastoreProxy.getCompanies()) {
list.add(Company.toSummaryDTO(entity));
}
return list;
}
@Override
public PublisherSummaryDTO getPublisherSummaryByLogin(String login) {
return Publisher.toSummaryDTO(DatastoreProxy.getPublisherByLogin(login));
}
@Override
public CompanySummaryDTO getCompanySummaryByLogin(String login) {
return Company.toSummaryDTO(DatastoreProxy.getCompanyByLogin(login));
}
@Override
public CompanySummaryDTO getCompanySummaryByPublisherId(Long id) {
Publisher publisher = DatastoreProxy.getPublisherById(id);
return publisher != null ? Company.toSummaryDTO(DatastoreProxy.getCompanyById(publisher.getCompanyId())) : null;
}
@Override
public List<PublisherDTO> getPublishersByCompanyId(Long id) {
List<PublisherDTO> list = new ArrayList<PublisherDTO>();
for (Publisher entity : DatastoreProxy.getPublishersByCompanyId(id)) {
list.add(Publisher.toDTO(entity));
}
return list;
}
@Override
public List<PublisherSummaryDTO> getPublisherSummariesByCompanyId(Long id) {
List<PublisherSummaryDTO> list = new ArrayList<PublisherSummaryDTO>();
for (Publisher entity : DatastoreProxy.getPublishersByCompanyId(id)) {
list.add(Publisher.toSummaryDTO(entity));
}
return list;
}
@Override
public List<PublisherDTO> getPublishersByGroupId(Long id) {
List<PublisherDTO> list = new ArrayList<PublisherDTO>();
for (Publisher entity : DatastoreProxy.getPublishersByGroupId(id)) {
list.add(Publisher.toDTO(entity));
}
return list;
}
@Override
public List<GroupDTO> getGroupsByCompanyId(Long id) {
return DatastoreProxy.getGroupsByCompanyId(id);
}
@Override
public List<ProductSummaryDTO> getProductSummariesBySlotOwnerId(Long id) {
List<ProductSummaryDTO> list = new ArrayList<ProductSummaryDTO>();
Publisher publisher = DatastoreProxy.getPublisherById(id);
if (publisher != null) {
// get products by publisher
for (Product entity : DatastoreProxy.getProductsByPublisherId(id)) {
list.add(Product.toSummaryDTO(entity));
}
} else {
Company company = DatastoreProxy.getCompanyById(id);
if (company != null) {
// get products by company
for (Publisher pub : DatastoreProxy.getPublishersByCompanyId(id)) {
for (Product product : DatastoreProxy.getProductsByPublisherId(pub.getId())) {
list.add(Product.toSummaryDTO(product));
}
}
}
}
return list;
}
@Override
public List<ProductSummaryDTO> getProductSummariesBySlotId(Long id) {
List<ProductSummaryDTO> list = new ArrayList<ProductSummaryDTO>();
Slot slot = DatastoreProxy.getSlotById(id);
if (slot != null) {
for (Long pId : slot.getProductIds()) {
list.add(Product.toSummaryDTO(DatastoreProxy.getProductById(pId)));
}
}
return list;
}
@Override
public SlotDTO getSlot(Long id) {
return Slot.toDTO(DatastoreProxy.getSlotById(id));
}
@Override
public Boolean deleteSlot(SlotDTO dto) {
try {
DatastoreProxy.deleteSlot(dto.getId());
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public Boolean withdrawSlot(SlotDTO dto) {
try {
dto.setStatus(SlotStatus.Cancelled);
updateSlot(dto);
QueueFactory.getQueue("gdata").add(TaskOptions.Builder.withUrl("/tasks/gdata/calendar").param("task", GoogleCalendarTaskTypes.DELETE).param("entityId", dto.getId().toString()));
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@Override
public SlotDTO updateSlot(SlotDTO dto) {
return Slot.toDTO(DatastoreProxy.updateSlot(dto));
}
@Override
public SlotDTO createSlot(SlotDTO dto) {
SlotDTO returnedDTO = Slot.toDTO((DatastoreProxy.createSlot(Slot.toEntity(null, dto))));
return returnedDTO;
}
@Override
public List<ProductSummaryDTO> getProductSummariesByPublisherId(Long id) {
List<ProductSummaryDTO> list = new ArrayList<ProductSummaryDTO>();
for (Product entity : DatastoreProxy.getProductsByPublisherId(id)) {
list.add(Product.toSummaryDTO(entity));
}
return list;
}
@Override
public List<SlotSummaryDTO> getSlotSummariesByOwnerId(Long id) {
List<SlotSummaryDTO> list = new ArrayList<SlotSummaryDTO>();
for (Slot entity : DatastoreProxy.getSlotsByOwnerId(id)) {
list.add(Slot.toSummaryDTO(entity));
}
return list;
}
@Override
public List<SlotDTO> getSlotsByOwnerAndStatus(Long companyId, Long publisherId, int status) {
List<Slot> temp = new ArrayList<Slot>();
List<SlotDTO> list = new ArrayList<SlotDTO>();
if (publisherId != null && publisherId != 0) {
temp.addAll(DatastoreProxy.getSlotsByOwnerIdAndStatus(publisherId, status));
} else if (companyId != null && companyId != 0) {
temp.addAll(DatastoreProxy.getSlotsByCompanyIdAndStatus(companyId, status));
} else {
temp.addAll(DatastoreProxy.getSlotsByStatus(status));
}
for (Slot entity : temp) {
list.add(Slot.toDTO(entity));
}
return list;
}
@Override
public List<SlotSummaryDTO> querySlotSummaries(Long companyId, Long publisherId, Date startDate, Date endDate, Boolean isConfigured, Boolean isSequential, Integer status) {
List<Slot> temp = new ArrayList<Slot>();
List<SlotSummaryDTO> list = new ArrayList<SlotSummaryDTO>();
if (publisherId != null && publisherId != 0) {
temp.addAll(DatastoreProxy.getSlotsByPublisherIdAndDates(publisherId, startDate, endDate, isConfigured, isSequential, status));
} else if (companyId != null && companyId != 0) {
temp.addAll(DatastoreProxy.getSlotsByCompanyIdAndDates(companyId, startDate, endDate, isConfigured, isSequential, status));
} else {
temp.addAll(DatastoreProxy.getSlotsByDates(startDate, endDate, isConfigured, isSequential, status));
}
for (Slot entity : temp) {
list.add(Slot.toSummaryDTO(entity));
}
return list;
}
}