code
stringlengths
3
1.18M
language
stringclasses
1 value
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; /** * This creates a Guice injector which will be used to inject servlets and classes. * * @author jimr@google.com (Jim Reardon) */ public class GuiceServletConfig extends GuiceServletContextListener { /** * Create and return a Guice injector. * * @see com.google.inject.servlet.GuiceServletContextListener#getInjector() */ @Override protected Injector getInjector() { return Guice.createInjector( new GuiceProviderModule(), new GuiceServletModule()); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Project; import java.util.List; /** * Server service for accessing project information. * * @author jimr@google.com (Jim Reardon) */ public interface ProjectService { public List<Project> query(String query); public List<Project> queryUserProjects(); public List<Project> queryProjectsUserHasEditAccessTo(); public Project getProjectById(long id); public Project getProjectByName(String name); public Long createProject(Project projInfo); public void updateProject(Project projInfo); public void removeProject(Project projInfo); public List<AccLabel> getLabels(long projectId); public List<Attribute> getProjectAttributes(long projectId); public Long createAttribute(Attribute attribute); public Attribute updateAttribute(Attribute attribute); public void removeAttribute(Attribute attribute); public void reorderAttributes(long projectId, List<Long> newOrder); public List<Component> getProjectComponents(long projectId); public Long createComponent(Component component); public Component updateComponent(Component component); public void removeComponent(Component component); public void reorderComponents(long projectId, List<Long> newOrder); public Capability getCapabilityById(long projectId, long capabilityId); public List<Capability> getProjectCapabilities(long projectId); public Capability createCapability(Capability capability); public void updateCapability(Capability capability); public void removeCapability(Capability capability); public void reorderCapabilities(long projectId, List<Long> newOrder); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import java.util.List; /** * Server service for accessing data related to a project (ie; Bugs, Tests). * * @author jimr@google.com (Jim Reardon) */ public interface DataService { public boolean isSignedOff(AccElementType type, Long elementId); public void setSignedOff(long projectId, AccElementType type, long elementId, boolean isSignedOff); public List<Signoff> getSignoffsByType(long projectId, AccElementType type); public List<DataSource> getDataSources(); public List<DataRequest> getProjectRequests(long projectId); public long addDataRequest(DataRequest request); public void updateDataRequest(DataRequest request); public void removeDataRequest(DataRequest request); public List<Filter> getFilters(long projectId); public long addFilter(Filter filter); public void updateFilter(Filter filter); public void removeFilter(Filter filter); public List<Bug> getProjectBugsById(long projectId); public void addBug(Bug bug); public void addBug(Bug bug, String asEmail); public void updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<Checkin> getProjectCheckinsById(long projectId); public void addCheckin(Checkin checkin); public void addCheckin(Checkin checkin, String asEmail); public void updateCheckinAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<TestCase> getProjectTestCasesById(long projectId); public void addTestCase(TestCase testCase); public void addTestCase(TestCase testCase, String asEmail); public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.HasLabels; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * This acts as a broker for the client when accessing project information, such as Attributes and * Components. Any operation will be checked using the user's current credentials, and fail if the * user doesn't have access to view or edit any project information. * * @author chrsmith@google.com (Chris Smith) */ @Singleton public class ProjectServiceImpl implements ProjectService { private static final Logger log = Logger.getLogger(ProjectServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final UserService userService; /** * Creates a new ProjectServiceImpl instance. Internally all methods will use the * PersistanceManager associated with JDOHelper.getPersistenceManagerFactory (meaning * jdoconfig.xml). */ @Inject public ProjectServiceImpl(PersistenceManagerFactory pmf, UserService userService) { this.pmf = pmf; this.userService = userService; } @SuppressWarnings("unchecked") @Override public List<Project> query(String query) { log.info("Querying: " + query); PersistenceManager pm = pmf.getPersistenceManager(); // TODO(jimr): this currently does not do a query, it just returns all public projects. Query jdoQuery = pm.newQuery(Project.class); jdoQuery.setOrdering("projectId asc"); List<Project> results = null; try { List<Project> returnedProjects = (List<Project>) jdoQuery.execute(); List<Project> safeToDisplayProjs = Lists.newArrayList(); for (Project returnedProject : returnedProjects) { if (userService.hasViewAccess(returnedProject)) { safeToDisplayProjs.add(returnedProject); } } results = ServletUtils.makeGwtSafe(safeToDisplayProjs, pm); populateCachedAccess(results); } finally { pm.close(); } return results; } private void populateCachedAccess(List<Project> projects) { for (Project p : projects) { populateCachedAccess(p); } } private void populateCachedAccess(Project p) { p.setCachedAccessLevel(userService.getAccessLevel(p)); } /** * Retrieves the list of projects relevant to the currently logged in user. */ @SuppressWarnings("unchecked") @Override public List<Project> queryUserProjects() { if (!userService.isUserLoggedIn()) { log.info("Querying user projects; user is not logged in."); return Lists.newArrayList(); } log.info("Querying user projects."); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Project.class); jdoQuery.setOrdering("projectId asc"); List<Project> results = null; try { List<Long> starredProjects = userService.getStarredProjects(); List<Project> returnedProjects = (List<Project>) jdoQuery.execute(); List<Project> projectsToReturn = Lists.newArrayList(); for (Project returnedProject : returnedProjects) { // Only returns the projects that are either: // * Starred by the user and have access (implicit or explicit). // * Granted VIEW or EDIT access explicitly. (Ignore public projects.) ProjectAccess access = userService.getAccessLevel(returnedProject); // If explicit, add it. Otherwise, check starred access (and implicit access). if (access.hasAccess(ProjectAccess.EXPLICIT_VIEW_ACCESS)) { projectsToReturn.add(returnedProject); } else if (access.hasAccess(ProjectAccess.VIEW_ACCESS) && starredProjects.contains(returnedProject.getProjectId())) { projectsToReturn.add(returnedProject); } } results = ServletUtils.makeGwtSafe(projectsToReturn, pm); populateCachedAccess(results); } finally { pm.close(); } return results; } /** * Returns the list of projects the currently logged in user has EDIT access to. */ @Override public List<Project> queryProjectsUserHasEditAccessTo() { ServletUtils.requireAccess(userService.isUserLoggedIn()); // Start with all starred projects and those granting explicit access. List<Project> projects = queryUserProjects(); List<Project> projectsToReturn = Lists.newArrayList(); for (Project project : projects) { if (userService.hasEditAccess(project)) { projectsToReturn.add(project); } } populateCachedAccess(projectsToReturn); return projectsToReturn; } @Override public Project getProjectById(long id) { log.info("Getting project: " + Long.toString(id)); PersistenceManager pm = pmf.getPersistenceManager(); try { Project retrievedProject = pm.getObjectById(Project.class, id); // Don't disclose that the project even exists if they don't have view access. if (retrievedProject != null && userService.hasViewAccess(retrievedProject)) { retrievedProject = ServletUtils.makeGwtSafe(retrievedProject, pm); populateCachedAccess(retrievedProject); return retrievedProject; } } finally { pm.close(); } return null; } @Override @SuppressWarnings("unchecked") public Project getProjectByName(String name) { log.info("Getting project with name: " + name); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Project.class); jdoQuery.declareParameters("String projectNameParam"); jdoQuery.setFilter("name == projectNameParam"); try { List<Project> returnedProjects = (List<Project>) jdoQuery.execute(name); log.info(String.format("Found %s projects with name %s", returnedProjects.size(), name)); for (Project target : returnedProjects) { if (userService.hasViewAccess(target)) { target = ServletUtils.makeGwtSafe(target, pm); populateCachedAccess(target); return target; } } } finally { pm.close(); } return null; } @Override public Long createProject(Project projInfo) { // The user must be logged in to create a project. ServletUtils.requireAccess(userService.isUserLoggedIn()); log.info("Creating new Project with name: " + projInfo.getName()); if (projInfo.getProjectId() != null) { throw new IllegalArgumentException( "You can only create a project with a null ID."); } PersistenceManager pm = pmf.getPersistenceManager(); try { // Automatically add the current user as an OWNER for the project. projInfo.addProjectOwner(userService.getEmail()); pm.makePersistent(projInfo); } finally { pm.close(); } return projInfo.getProjectId(); } @Override public void updateProject(Project projInfo) { if (projInfo.getProjectId() == null) { throw new IllegalArgumentException( "projInfo has not been saved. Please call createProject first."); } ServletUtils.requireAccess(userService.hasEditAccess(projInfo.getProjectId())); log.info("Updating Project: " + projInfo.getProjectId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); Project oldProject; try { oldProject = pm.getObjectById(Project.class, projInfo.getProjectId()); List<String> oldOwners = oldProject.getProjectOwners(); List<String> oldEditors = oldProject.getProjectEditors(); List<String> oldViewers = oldProject.getProjectViewers(); // If they're not an owner, keep the old list of owners around. if (!userService.hasOwnerAccess(projInfo.getProjectId())) { projInfo.setIsPubliclyVisible(oldProject.getIsPubliclyVisible()); projInfo.setProjectOwners(oldProject.getProjectOwners()); } pm.makePersistent(projInfo); log.info("Notifying users of any changes to access level"); String from = userService.getEmail(); List<String> added = StringUtil.subtractList(projInfo.getProjectOwners(), oldOwners); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "owner", projInfo.getName(), projInfo.getProjectId().toString()); } List<String> removed = StringUtil.subtractList(oldOwners, projInfo.getProjectOwners()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "owner", projInfo.getName(), projInfo.getProjectId().toString()); } added = StringUtil.subtractList(projInfo.getProjectEditors(), oldEditors); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "editor", projInfo.getName(), projInfo.getProjectId().toString()); } removed = StringUtil.subtractList(oldEditors, projInfo.getProjectEditors()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "editor", projInfo.getName(), projInfo.getProjectId().toString()); } added = StringUtil.subtractList(projInfo.getProjectViewers(), oldViewers); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "viewer", projInfo.getName(), projInfo.getProjectId().toString()); } removed = StringUtil.subtractList(oldViewers, projInfo.getProjectViewers()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "viewer", projInfo.getName(), projInfo.getProjectId().toString()); } } finally { pm.close(); } } @Override public void removeProject(Project projInfo) { if (projInfo.getProjectId() == null) { log.info("Attempting to delete unsaved project. Ignoring."); return; } ServletUtils.requireAccess(userService.hasOwnerAccess(projInfo.getProjectId())); PersistenceManager pm = pmf.getPersistenceManager(); try { Project projToDelete = pm.getObjectById(Project.class, projInfo.getProjectId()); // TODO(jimr): This delete could succeed but successive removes might fail, leaving dangling // data. We should retry or do something to assure complete destruction. // TODO(jimr): Undo? pm.deletePersistent(projToDelete); // Delete any child attributes, components, or capabilities. removeObjectsWithFieldValue(pm, Attribute.class, "parentProjectId", projInfo.getProjectId()); removeObjectsWithFieldValue(pm, Component.class, "parentProjectId", projInfo.getProjectId()); removeObjectsWithFieldValue(pm, Capability.class, "parentProjectId", projInfo.getProjectId()); // TODO(chrsmith): What about enabled data providers? For example, bugs or checkin data // associated with this project? We need to clear those out as well. } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<AccLabel> getLabels(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting labels for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(AccLabel.class); jdoQuery.setFilter("projectId == projectIdParam"); jdoQuery.declareParameters("Long projectIdParam"); try { List<AccLabel> labels = (List<AccLabel>) jdoQuery.execute(projectId); return ServletUtils.makeGwtSafe(labels, pm); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Attribute> getProjectAttributes(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Attributes for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Attribute.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Attribute> returnedAttributes = (List<Attribute>) jdoQuery.execute(projectId); returnedAttributes = ServletUtils.makeGwtSafe(returnedAttributes, pm); populateLabels(returnedAttributes, pm); return returnedAttributes; } finally { pm.close(); } } /** * Populates labels for a HasLabels item. * * @param <T> An object that HasLabels. * @param item The item to get labels for. * @param pm A persistence manager object. */ private <T extends HasLabels> void populateLabels(T item, PersistenceManager pm) { item.setAccLabels(getLabelsForItem(item, pm)); } /** * Populates labels for a list of HasLabels items. All items MUST be for the same project * and of the same type (ie, all Attributes). * * IMPORTANT: you probably want to detach your object before calling this. * * @param <T> An object that HasLabels. * @param items The items to get labels for. * @param pm A persistence manager object. */ @SuppressWarnings("unchecked") private <T extends HasLabels> void populateLabels(List<T> items, PersistenceManager pm) { if (items.size() > 0) { Map<Long, T> idToItem = Maps.newHashMap(); for (T item : items) { idToItem.put(item.getId(), item); } T item = items.get(0); AccElementType type = item.getElementType(); Long parentProjectId = item.getParentProjectId(); Query query = pm.newQuery(AccLabel.class); query.declareParameters("AccElementType elementTypeParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && projectId == projectIdParam"); List<AccLabel> labels = (List<AccLabel>) query.execute(type, parentProjectId); log.info("Found labels: " + labels.size()); for (AccLabel label : labels) { item = idToItem.get(label.getElementId()); if (item != null) { log.info("Putting label where it belongs: " + label.getLabelText()); item.addLabel(label); } } } } @SuppressWarnings("unchecked") private <T extends HasLabels> List<AccLabel> getLabelsForItem(T item, PersistenceManager pm) { Query query = pm.newQuery(AccLabel.class); query.declareParameters( "AccElementType elementTypeParam, Long elementIdParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && elementId == elementIdParam && " + "projectId == projectIdParam"); List<AccLabel> labels = (List<AccLabel>) query.execute(item.getElementType(), item.getId(), item.getParentProjectId()); // This constructs a new, real list -- the list returned by the above execution is a lazy-loaded // streaming query. That doesn't serialize. return Lists.newArrayList(labels); } /** * Saves labels for an item. * * This is not extremely necessary, but for simplicity ('always call persistLabels') it's here. * * @param <T> An object that HasLabels. * @param item The item to save the labels for. * @param pm A persistence mananger. */ private <T extends HasLabels> void persistLabels(T item, PersistenceManager pm) { List<AccLabel> toDelete = Lists.newArrayList(); Set<String> newLabelKeys = Sets.newHashSet(); for (AccLabel label : item.getAccLabels()) { if (label.getId() != null) { newLabelKeys.add(label.getId()); } } List<AccLabel> currentLabels = getLabelsForItem(item, pm); for (AccLabel label : currentLabels) { if (!newLabelKeys.contains(label.getId())) { toDelete.add(label); } } pm.deletePersistentAll(toDelete); // And add the new ones. pm.makePersistentAll(item.getAccLabels()); } private <T extends HasLabels> void updateLabelElementIds(T item, Long id) { for (AccLabel label : item.getAccLabels()) { label.setElementId(id); } } private <T extends HasLabels> void deleteLabels(T item, PersistenceManager pm) { pm.deletePersistentAll(item.getAccLabels()); } @Override public Long createAttribute(Attribute attribute) { ServletUtils.requireAccess(userService.hasEditAccess(attribute.getParentProjectId())); if (attribute.getAttributeId() != null) { throw new IllegalArgumentException( "You can only create an attribute with a null ID."); } log.info("Creating new Attribute with name: " + attribute.getName()); attribute.setName(attribute.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(attribute); // If we have labels, update their element ID now that we have an ID. if (attribute.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(attribute, attribute.getAttributeId()); pm = pmf.getPersistenceManager(); persistLabels(attribute, pm); } } finally { pm.close(); } return attribute.getAttributeId(); } @Override public Attribute updateAttribute(Attribute attribute) { if (attribute.getAttributeId() == null) { throw new IllegalArgumentException( "attribute has not been saved. Please call createAttribute first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(attribute.getParentProjectId())); log.info("Updating Attribute: " + attribute.getAttributeId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Attribute oldAttribute = pm.getObjectById(Attribute.class, attribute.getAttributeId()); if (oldAttribute.getParentProjectId() != attribute.getParentProjectId()) { log.severe("Possible attack -- attribute sent in and attribute being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } persistLabels(attribute, pm); pm.makePersistent(attribute); attribute = ServletUtils.makeGwtSafe(attribute, pm); populateLabels(attribute, pm); attribute.setAccLabels(ServletUtils.makeGwtSafe(attribute.getAccLabels(), pm)); return attribute; } finally { pm.close(); } } @Override public void removeAttribute(Attribute attribute) { if (attribute.getAttributeId() == null) { log.info("Attempting to delete unsaved Attribute. Ignoring."); return; } log.info("Removing Attribute: " + attribute.getAttributeId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Attribute attributeToDelete = pm.getObjectById(Attribute.class, attribute.getAttributeId()); ServletUtils.requireAccess(userService.hasEditAccess(attributeToDelete.getParentProjectId())); pm.deletePersistent(attributeToDelete); deleteLabels(attribute, pm); // Delete any child capabilities. removeObjectsWithFieldValue(pm, Capability.class, "attributeId", attribute.getAttributeId()); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public void reorderAttributes(long projectId, List<Long> newOrdering) { log.info("Reordering Attributes for project: " + Long.toString(projectId)); Function<Attribute, Long> getId = new Function<Attribute, Long>() { @Override public Long apply(Attribute input) { return input.getAttributeId(); } }; Setter<Attribute> setId = new Setter<Attribute>() { @Override public boolean apply(Attribute input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Attribute.class, newOrdering, getId, setId); } @SuppressWarnings("unchecked") @Override public List<Component> getProjectComponents(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Components for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Component.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Component> returnedComponents = (List<Component>) jdoQuery.execute(projectId); returnedComponents = ServletUtils.makeGwtSafe(returnedComponents, pm); populateLabels(returnedComponents, pm); return returnedComponents; } finally { pm.close(); } } @Override public Long createComponent(Component component) { ServletUtils.requireAccess(userService.hasEditAccess(component.getParentProjectId())); if (component.getComponentId() != null) { throw new IllegalArgumentException( "You can only create a component with a null ID."); } log.info("Creating new Component with name: " + component.getName()); component.setName(component.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(component); // If we have labels, update their element ID now that we have an ID. if (component.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(component, component.getId()); pm = pmf.getPersistenceManager(); persistLabels(component, pm); } } finally { pm.close(); } return component.getComponentId(); } @Override public Component updateComponent(Component component) { if (component.getComponentId() == null) { throw new IllegalArgumentException( "component has not been saved. Please call createComponent first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(component.getParentProjectId())); log.info("Updating Component: " + component.getComponentId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Component oldComponent = pm.getObjectById(Component.class, component.getComponentId()); if (oldComponent.getParentProjectId() != component.getParentProjectId()) { log.severe("Possible attack -- component sent in and component being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } persistLabels(component, pm); pm.makePersistent(component); component = ServletUtils.makeGwtSafe(component, pm); populateLabels(component, pm); component.setAccLabels(ServletUtils.makeGwtSafe(component.getAccLabels(), pm)); return component; } finally { pm.close(); } } @Override public void removeComponent(Component component) { if (component.getComponentId() == null) { log.info("Attempting to delete unsaved Component. Ignoring."); return; } log.info("Removing Component: " + component.getComponentId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Component componentToDelete = pm.getObjectById(Component.class, component.getComponentId()); ServletUtils.requireAccess(userService.hasEditAccess(componentToDelete.getParentProjectId())); pm.deletePersistent(componentToDelete); deleteLabels(componentToDelete, pm); // Delete any child capabilities. removeObjectsWithFieldValue(pm, Capability.class, "componentId", component.getComponentId()); } finally { pm.close(); } } @SuppressWarnings("unchecked") private <T> void setOrder(long projectId, Class<T> clazz, List<Long> order, Function<T, Long> getId, Setter<T> applyOrder) { log.info("setOrder executing with " + order.size() + " items passed in."); ServletUtils.requireAccess(userService.hasEditAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Query jdoQuery = pm.newQuery(clazz); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.declareParameters("Long parentProjectParam"); List<T> items = (List<T>) jdoQuery.execute(projectId); Map<Long, Integer> lookup = Maps.newHashMap(); for (int i = 0; i < order.size(); i++) { Long id = order.get(i); lookup.put(id, i); } for (T item : items) { Long id = getId.apply(item); Integer newIndex = lookup.get(id); if (newIndex != null) { if (applyOrder.apply(item, newIndex)) { pm.makePersistent(item); } } else { log.warning("Project contains item not covered in new ordering - ID: " + id); } } } finally { pm.close(); } log.info("setOrder complete"); } @Override public void reorderCapabilities(long projectId, List<Long> newOrdering) { log.info("Reordering capabilities for project: " + Long.toString(projectId)); Function<Capability, Long> getId = new Function<Capability, Long>() { @Override public Long apply(Capability input) { return input.getCapabilityId(); } }; Setter<Capability> setId = new Setter<Capability>() { @Override public boolean apply(Capability input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Capability.class, newOrdering, getId, setId); } @SuppressWarnings("unchecked") @Override public void reorderComponents(long projectId, List<Long> newOrdering) { log.info("Reordering Components for project: " + Long.toString(projectId)); Function<Component, Long> getId = new Function<Component, Long>() { @Override public Long apply(Component input) { return input.getComponentId(); } }; Setter<Component> setId = new Setter<Component>() { @Override public boolean apply(Component input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Component.class, newOrdering, getId, setId); } private interface Setter<F> { boolean apply(F input, long value); } @Override @SuppressWarnings("unchecked") public Capability getCapabilityById(long projectId, long capabilityId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting capability for project by id: " + Long.toString(projectId) + ", " + Long.toString(capabilityId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Capability.class); jdoQuery.setFilter( "parentProjectId == parentProjectParam && capabilityId == capabilityIdParam"); jdoQuery.declareParameters("Long parentProjectParam, Long capabilityIdParam"); try { List<Capability> results = (List<Capability>) jdoQuery.execute( projectId, capabilityId); if (results.size() > 0) { Capability c = results.get(0); c = ServletUtils.makeGwtSafe(c, pm); populateLabels(c, pm); return c; } else { return null; } } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Capability> getProjectCapabilities(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Capabilities for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Capability.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Capability> returnedCapabilities = (List<Capability>) jdoQuery.execute(projectId); returnedCapabilities = ServletUtils.makeGwtSafe(returnedCapabilities, pm); populateLabels(returnedCapabilities, pm); return returnedCapabilities; } finally { pm.close(); } } @Override public Capability createCapability(Capability capability) { ServletUtils.requireAccess(userService.hasEditAccess(capability.getParentProjectId())); if (capability.getCapabilityId() != null) { throw new IllegalArgumentException( "You can only create a capability with a null ID."); } log.info("Creating new Capability with name: " + capability.getName()); capability.setName(capability.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(capability); capability = ServletUtils.makeGwtSafe(capability, pm); // If we have labels, update their element ID now that we have an ID. if (capability.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(capability, capability.getId()); pm = pmf.getPersistenceManager(); persistLabels(capability, pm); } return capability; } finally { pm.close(); } } @Override public void updateCapability(Capability capability) { if (capability.getCapabilityId() == null) { throw new IllegalArgumentException( "Capability has not been saved. Please call createCapability first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(capability.getParentProjectId())); log.info("Updating capability: " + capability.getCapabilityId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Capability oldCapability = pm.getObjectById(Capability.class, capability.getCapabilityId()); if (oldCapability.getParentProjectId() != capability.getParentProjectId()) { log.severe("Possible attack -- capability sent in and capability being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } pm.makePersistent(capability); persistLabels(capability, pm); } finally { pm.close(); } } @Override public void removeCapability(Capability capability) { if (capability.getCapabilityId() == null) { log.info("Attempting to delete unsaved Component. Ignoring."); return; } log.info("Removing Capability: " + capability.getCapabilityId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Capability capabilityToDelete = pm.getObjectById( Capability.class, capability.getCapabilityId()); ServletUtils.requireAccess(userService.hasEditAccess( capabilityToDelete.getParentProjectId())); pm.deletePersistent(capabilityToDelete); deleteLabels(capabilityToDelete, pm); } finally { pm.close(); } } /** * Deletes all stored objects of the given type with the field matching the specified ID. * Primarily this is used for deleting dependent, child objects when the parent is removed. * * @param pm the PersistenceManager used to perform the deletion operation. * @param type the type of the object to be removed. * @param fieldName the name on the object to check. * @param fieldValue the value which must match in order for the object to get deleted. */ private <T> void removeObjectsWithFieldValue( PersistenceManager pm, Class<T> type, String fieldName, long fieldValue) throws IllegalArgumentException { // Do a brief sanity check on the field name. fieldName = fieldName.trim(); if ((fieldName.contains(" ")) || (fieldName.contains(";"))) { throw new IllegalArgumentException(); } StringBuilder message = new StringBuilder(); message.append("Deleting all "); message.append(type.getCanonicalName()); message.append(" with '"); message.append(fieldName); message.append("' equal to "); message.append(Long.toString(fieldValue)); log.info(message.toString()); Query objectsToDeleteQuery = pm.newQuery(type); objectsToDeleteQuery.setFilter(fieldName + " == fieldValueParam"); objectsToDeleteQuery.declareParameters("int fieldValueParam"); objectsToDeleteQuery.deletePersistentAll(fieldValue); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.DatumType; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.model.UploadedDatum; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * Implementation of the DataRequestService, for tracking project requests for external * data. This data is also exposed via the DataRequest servlet. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ @Singleton public class DataServiceImpl implements DataService { private static final Logger log = Logger.getLogger(DataServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final UserService userService; /** * Creates a new DataServiceImpl instance. */ @Inject public DataServiceImpl(PersistenceManagerFactory pmf, UserService userService) { this.pmf = pmf; this.userService = userService; } @Override public boolean isSignedOff(AccElementType type, Long elementId) { Signoff signoff = getSignoff(type, elementId); return signoff == null ? false : signoff.getSignedOff(); } @Override public void setSignedOff(long projectId, AccElementType type, long elementId, boolean isSignedOff) { ServletUtils.requireAccess(userService.hasEditAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Signoff signoff = getSignoff(type, elementId); if (signoff == null) { signoff = new Signoff(); signoff.setParentProjectId(projectId); signoff.setElementType(type); signoff.setElementId(elementId); } else { if (signoff.getParentProjectId() != projectId) { ServletUtils.requireAccess(false); } } signoff.setSignedOff(isSignedOff); pm.makePersistent(signoff); } finally { pm.close(); } } @Override @SuppressWarnings("unchecked") public List<Signoff> getSignoffsByType(long projectId, AccElementType type) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Query query = pm.newQuery(Signoff.class); query.declareParameters("AccElementType elementTypeParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && parentProjectId == projectIdParam"); List<Signoff> results = (List<Signoff>) query.execute(type, projectId); return ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } } @SuppressWarnings("unchecked") private Signoff getSignoff(AccElementType type, Long elementId) { PersistenceManager pm = pmf.getPersistenceManager(); try { Query query = pm.newQuery(Signoff.class); query.declareParameters("AccElementType elementTypeParam, Long elementIdParam"); query.setFilter("elementType == elementTypeParam && elementId == elementIdParam"); List<Signoff> results = (List<Signoff>) query.execute(type, elementId); if (results.size() > 0) { Signoff signoff = results.get(0); ServletUtils.requireAccess(userService.hasViewAccess(signoff.getParentProjectId())); return ServletUtils.makeGwtSafe(signoff, pm); } else { return null; } } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<DataSource> getDataSources() { boolean isInternal = userService.isInternalUser(); PersistenceManager pm = pmf.getPersistenceManager(); List<DataSource> results = null; log.info("Retrieving data sources."); try { Query query = pm.newQuery(DataSource.class); if (isInternal == false) { query.setFilter("internalOnly == false"); log.info("Only retrieving external friendly sources, not an internal user."); } results = (List<DataSource>) query.execute(); results = ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } log.info("Returning results: " + results.size()); return results; } @SuppressWarnings("unchecked") @Override public List<DataRequest> getProjectRequests(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Data Requests for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(DataRequest.class); jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); List<DataRequest> results = null; try { List<DataRequest> returnedRequests = (List<DataRequest>) jdoQuery.execute(projectId); results = ServletUtils.makeGwtSafe(returnedRequests, pm); } finally { pm.close(); } return results; } @Override public long addDataRequest(DataRequest request) { ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Creating new Data Request for source: " + request.getDataSourceName()); request.setDataSourceName(request.getDataSourceName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(request); } finally { pm.close(); } return request.getRequestId(); } @Override public void updateDataRequest(DataRequest request) { if (request.getRequestId() == null) { throw new IllegalArgumentException( "Request has not been saved. Please call addDataRequest first."); } ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Updating DataRequest: " + request.getRequestId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(request); } finally { pm.close(); } } @Override public void removeDataRequest(DataRequest request) { if (request.getRequestId() == null) { log.info("Attempting to delete unsaved DataRequest. Ignoring."); return; } ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Removing DataRequest: " + request.getRequestId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { DataRequest requestToDelete = pm.getObjectById(DataRequest.class, request.getRequestId()); pm.deletePersistent(requestToDelete); } finally { pm.close(); } } @Override public List<Filter> getFilters(long projectId) { return getFiltersByType(projectId, null); } @SuppressWarnings("unchecked") private List<Filter> getFiltersByType(long projectId, DatumType filterType) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Filters for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Filter.class); List<Filter> jdoResults; try { if (filterType == null) { jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoResults = (List<Filter>) jdoQuery.execute(projectId); } else { jdoQuery.declareParameters("Long parentProjectParam, DatumType filterTypeParam"); jdoQuery.setFilter( "parentProjectId == parentProjectParam && filterType == filterTypeParam"); jdoResults = (List<Filter>) jdoQuery.execute(projectId, filterType); } return ServletUtils.makeGwtSafe(jdoResults, pm); } finally { pm.close(); } } @Override public long addFilter(Filter filter) { ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Adding filter for project: " + filter.getParentProjectId()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(filter); } finally { pm.close(); } return filter.getId(); } @Override public void updateFilter(Filter filter) { if (filter.getId() == null) { throw new IllegalArgumentException( "Filter has not been saved. Please call addFilter first."); } ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Updating filter: " + filter.getId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(filter); } finally { pm.close(); } } @Override public void removeFilter(Filter filter) { if (filter.getId() == null) { log.info("Attempting to delete unsaved Filter. Ignoring."); return; } ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Deleting filter: " + filter.getId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Filter filterToDelete = pm.getObjectById(Filter.class, filter.getId()); pm.deletePersistent(filterToDelete); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Bug> getProjectBugsById(long projectId) { return getProjectData(Bug.class, projectId); } @SuppressWarnings("unchecked") @Override public void updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId) { updateAssociations(Bug.class, bugId, attributeId, componentId, capabilityId); } /** * Try to upload a new bug into the GAE datastore. If a bug with the same Bug ID already exists, * it will be updated. This is a friendly function; it will not throw if there's an error * adding the bug. */ @Override public void addBug(Bug bug) { addBug(bug, userService.getEmail()); } @SuppressWarnings("unchecked") @Override public void addBug(Bug bug, String asEmail) { log.info("Trying to add Bug: " + bug.getTitle() + " for project " + bug.getParentProjectId()); ServletUtils.requireAccess(userService.hasEditAccess(bug.getParentProjectId(), asEmail)); // Trim long fields. bug.setTitle(StringUtil.trimString(bug.getTitle())); saveOrUpdateDatum(bug); } @SuppressWarnings("unchecked") @Override public List<Checkin> getProjectCheckinsById(long projectId) { return getProjectData(Checkin.class, projectId); } @Override public void addCheckin(Checkin checkin) { addCheckin(checkin, userService.getEmail()); } /** * Try to upload a new Checkin into the GAE datastore. If a Checkin with the same Checkin ID * already exists, it will be updated. */ @SuppressWarnings("unchecked") @Override public void addCheckin(Checkin checkin, String asEmail) { log.info("Trying to add Checkin: " + checkin.getSummary()); ServletUtils.requireAccess(userService.hasEditAccess(checkin.getParentProjectId(), asEmail)); checkin.setSummary(StringUtil.trimString(checkin.getSummary())); saveOrUpdateDatum(checkin); } @SuppressWarnings("unchecked") @Override public void updateCheckinAssociations(long checkinId, long attributeId, long componentId, long capabilityId) { updateAssociations(Checkin.class, checkinId, attributeId, componentId, capabilityId); } @SuppressWarnings("unchecked") @Override public List<TestCase> getProjectTestCasesById(long projectId) { return getProjectData(TestCase.class, projectId); } @SuppressWarnings("unchecked") @Override public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId) { updateAssociations(TestCase.class, testCaseId, attributeId, componentId, capabilityId); } @Override public void addTestCase(TestCase test) { addTestCase(test, userService.getEmail()); } /** * Try to upload a new bug into the GAE datastore. If a test case with the same ID already * exists, it will be updated. */ @SuppressWarnings("unchecked") @Override public void addTestCase(TestCase test, String asEmail) { log.info("Trying to add Test: " + test.getTitle()); ServletUtils.requireAccess(userService.hasEditAccess(test.getParentProjectId(), asEmail)); // Trim long fields. test.setTitle(StringUtil.trimString(test.getTitle())); saveOrUpdateDatum(test); } @SuppressWarnings("unchecked") private <T extends UploadedDatum> List<T> getProjectData(Class<T> clazz, long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting data for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(clazz); jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("externalId asc"); List<T> projectData = null; try { List<T> results = (List<T>) jdoQuery.execute(projectId); projectData = ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } return projectData; } /** * Saves a new datum, or updates an existing datum in the database if it already exists. * * @param datum */ @SuppressWarnings("unchecked") private <T extends UploadedDatum> void saveOrUpdateDatum(T datum) { PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(datum.getClass()); jdoQuery.declareParameters("Long parentProjectParam, Long externalIdParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam && externalId == externalIdParam"); try { // There are two ways an existing item may exist: the same primary key, or the same // parent project ID and bug ID. T oldDatum = null; if (datum.getInternalId() != null) { // If it's the same primary key, make sure it makes sense to overwrite it. The existing // bug should be non-null (we shouldn't have a pkey if it's unsaved already) and match // projects. oldDatum = (T) pm.getObjectById(datum.getClass(), datum.getInternalId()); ServletUtils.requireAccess(oldDatum != null); ServletUtils.requireAccess(oldDatum.getParentProjectId() == datum.getParentProjectId()); } else { // Try to load by a combination of project and external IDs. List<T> results = (List<T>) jdoQuery.execute(datum.getParentProjectId(), datum.getExternalId()); if (results.size() > 0) { oldDatum = results.get(0); } } if (oldDatum != null) { datum.setInternalId(oldDatum.getInternalId()); transferAssignments(oldDatum, datum); } else { applyFilters(datum); } pm.makePersistent(datum); } finally { pm.close(); } } private <T extends UploadedDatum> void updateAssociations(Class<T> clazz, long internalId, long attributeId, long componentId, long capabilityId) { PersistenceManager pm = pmf.getPersistenceManager(); try { T datum = pm.getObjectById(clazz, internalId); if (datum == null) { log.info("No results when querying for datum ID: " + internalId); return; } ServletUtils.requireAccess(userService.hasEditAccess(datum.getParentProjectId())); boolean updated = false; if (attributeId >= 0) { datum.setTargetAttributeId(attributeId == 0 ? null : attributeId); updated = true; } if (componentId >= 0) { datum.setTargetComponentId(componentId == 0 ? null : componentId); updated = true; } if (capabilityId >= 0) { datum.setTargetCapabilityId(capabilityId == 0 ? null : capabilityId); updated = true; } if (updated) { pm.makePersistent(datum); } } finally { pm.close(); } } /** * Iff the old datum (from the database) has an assigned attribute, component, or capability * AND the new datum doesn't have an assignment, we copy the old assignment over. * * @param oldDatum the old item. * @param newDatum the new item; it will have the a/c/c set from the old item. */ private void transferAssignments(UploadedDatum oldDatum, UploadedDatum newDatum) { if (positive(oldDatum.getTargetAttributeId()) && !positive(newDatum.getTargetAttributeId())) { newDatum.setTargetAttributeId(oldDatum.getTargetAttributeId()); } if (positive(oldDatum.getTargetComponentId()) && !positive(newDatum.getTargetComponentId())) { newDatum.setTargetComponentId(oldDatum.getTargetComponentId()); } if (positive(oldDatum.getTargetCapabilityId()) && !positive(newDatum.getTargetCapabilityId())) { newDatum.setTargetCapabilityId(oldDatum.getTargetCapabilityId()); } } private void applyFilters(UploadedDatum item) { // TODO(jimr): This is a poor way to filter items... it's a stop-gap solution until the recently // announced Full Text Search is available for the AppEngine datastore. List<Filter> filters = getFiltersByType(item.getParentProjectId(), item.getDatumType()); for (Filter filter : filters) { filter.apply(item); } } private boolean positive(Long value) { return value != null && value > 0; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; import com.google.appengine.api.utils.SystemProperty; import com.google.appengine.api.utils.SystemProperty.Environment.Value; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.model.UserInfo; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * Implementation of UserService. Returns user and security information. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UserServiceImpl implements UserService { private static final String LOCAL_DOMAIN = System.getProperty("com.google.testing.testify.risk.frontend.localdomain"); private static final boolean WHITELISTING_ENABLED = Boolean.valueOf(System.getProperty("com.google.testing.testify.risk.frontend.whitelisting")); private static final Logger log = Logger.getLogger(UserServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final com.google.appengine.api.users.UserService userService; @Inject public UserServiceImpl(PersistenceManagerFactory pmf) { this.pmf = pmf; // TODO(jimr): Inject this. this.userService = UserServiceFactory.getUserService(); } @Override public boolean isUserLoggedIn() { return getEmail() != null; } @Override public String getEmail() { User user = userService.getCurrentUser(); return user == null ? null : user.getEmail(); } @Override public boolean isWhitelistingEnabled() { return WHITELISTING_ENABLED; } @Override public boolean isWhitelisted() { if (isInternalUser()) { return true; } UserInfo user = getCurrentUserInfo(pmf.getPersistenceManager(), false); if (user == null) { return false; } return user.getIsWhitelisted(); } @Override public boolean isInternalUser() { if (isDevMode()) { return true; } String email = getEmail(); if (email == null || LOCAL_DOMAIN == null) { return false; } return email.endsWith(LOCAL_DOMAIN); } @Override public LoginStatus getLoginStatus(String returnUrl) { User user = userService.getCurrentUser(); String email = null; String url; if (user == null) { email = ""; url = userService.createLoginURL(returnUrl); } else { email = user.getEmail(); url = userService.createLogoutURL(returnUrl); } return new LoginStatus(user != null, url, email); } @Override public boolean hasAdministratorAccess() { return userService.isUserAdmin(); } @Override public boolean hasViewAccess(long projectId) { return hasAccess(ProjectAccess.VIEW_ACCESS, projectId); } @Override public boolean hasViewAccess(Project project) { return hasAccess(ProjectAccess.VIEW_ACCESS, project, getEmail()); } @Override public boolean hasEditAccess(long projectId) { return hasEditAccess(projectId, getEmail()); } @Override public boolean hasEditAccess(Project project) { return hasAccess(ProjectAccess.VIEW_ACCESS, project, getEmail()); } @Override public boolean hasEditAccess(long projectId, String asEmail) { return hasAccess(ProjectAccess.EDIT_ACCESS, projectId, asEmail); } @Override public boolean hasOwnerAccess(long projectId) { return hasAccess(ProjectAccess.OWNER_ACCESS, projectId); } @Override public boolean hasAccess(ProjectAccess accessLevel, long projectId) { return hasAccess(accessLevel, projectId, getEmail()); } @Override public boolean hasAccess(ProjectAccess accessLevel, long projectId, String asEmail) { return hasAccess(accessLevel, getProject(projectId), asEmail); } private boolean hasAccess(ProjectAccess accessLevel, Project project, String asEmail) { if (project == null) { log.warning("Call to hasAccess with a null project."); return false; } ProjectAccess accessHas = getAccessLevel(project, asEmail); log.info("Access has: " + accessHas.name() + " Access desired: " + accessLevel.name()); return accessHas.hasAccess(accessLevel); } @Override public ProjectAccess getAccessLevel(long projectId) { return getAccessLevel(getProject(projectId), getEmail()); } @Override public ProjectAccess getAccessLevel(Project project) { return getAccessLevel(project, getEmail()); } @Override public ProjectAccess getAccessLevel(long projectId, String asEmail) { return getAccessLevel(getProject(projectId), asEmail); } private ProjectAccess getAccessLevel(Project project, String asEmail) { if (project == null) { log.warning("Call to getAccessLevel with a null project."); return ProjectAccess.NO_ACCESS; } if (asEmail == null) { if (project.getIsPubliclyVisible()) { return ProjectAccess.VIEW_ACCESS; } else { return ProjectAccess.NO_ACCESS; } } else { if (hasAdministratorAccess()) { return ProjectAccess.ADMINISTRATOR_ACCESS; } else if (project.getProjectOwners().contains(asEmail)) { return ProjectAccess.OWNER_ACCESS; } else if (project.getProjectEditors().contains(asEmail)) { return ProjectAccess.EDIT_ACCESS; } else if (project.getProjectViewers().contains(asEmail)) { return ProjectAccess.EXPLICIT_VIEW_ACCESS; } else if (project.getIsPubliclyVisible()) { return ProjectAccess.VIEW_ACCESS; } else { return ProjectAccess.NO_ACCESS; } } } @Override public List<Long> getStarredProjects() { log.info("Getting starred projects for current user."); PersistenceManager pm = pmf.getPersistenceManager(); List<Long> starredProjects = Lists.newArrayList(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); // Copy list items over since we cannot return the server-side list type to client-side code. if (userInfo != null) { for (long projectId : userInfo.getStarredProjects()) { starredProjects.add(projectId); } } } finally { pm.close(); } return starredProjects; } @Override public void starProject(long projectId) { log.info("Starring project: " + projectId); PersistenceManager pm = pmf.getPersistenceManager(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); if (userInfo != null) { userInfo.starProject(projectId); pm.makePersistent(userInfo); } } finally { pm.close(); } } @Override public void unstarProject(long projectId) { log.info("Unstarring project: " + projectId); PersistenceManager pm = pmf.getPersistenceManager(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); if (userInfo != null) { userInfo.unstarProject(projectId); pm.makePersistent(userInfo); } } finally { pm.close(); } } @Override public boolean isDevMode() { Value env = SystemProperty.environment.value(); log.info("System environment: " + env.toString()); return env.equals(SystemProperty.Environment.Value.Development); } /** * Returns all information Testify knows about the currently logged in user. If the logged in user * is not currently in Testify, a new UserInfo entry will be created. Also, will return null if * the user is not currently logged in. * * @param pm The PersistenceManager session for which the UserInfo object was returned. */ private UserInfo getCurrentUserInfo(PersistenceManager pm, boolean createIfMissing) { User appEngineUser = userService.getCurrentUser(); if (appEngineUser == null) { log.info("Unable to get user info. User is not logged in."); return null; } // If they are logged in, get the Testify UserInfo record on file. If unavailable, create a new // entry. String loggedInUserId = appEngineUser.getUserId(); String currentEmail = appEngineUser.getEmail(); Query jdoQuery = pm.newQuery(UserInfo.class); jdoQuery.declareParameters("String userIdParam"); jdoQuery.setFilter("userId == userIdParam"); log.info("Querying for user " + currentEmail + " by id " + loggedInUserId); UserInfo user = queryAndReturnFirst(jdoQuery, loggedInUserId); if (user != null) { // Update email address if missing or different. if (!currentEmail.equals(user.getCurrentEmail())) { log.info("Adding or updating email for " + currentEmail + " id " + loggedInUserId); user.setCurrentEmail(currentEmail); pm.makePersistent(user); } } else { // Try to find by email instead. log.info("Querying for user " + currentEmail + " by email instead."); jdoQuery = pm.newQuery(UserInfo.class); jdoQuery.declareParameters("String currentEmailParam"); jdoQuery.setFilter("currentEmail == currentEmailParam"); user = queryAndReturnFirst(jdoQuery, currentEmail); if (user != null) { // Add the user's user ID since we now know it. if (user.getUserId() == null || user.getUserId().equals("")) { log.info("Adding user ID for " + currentEmail + "."); user.setUserId(appEngineUser.getUserId()); pm.makePersistent(user); } else { log.severe("Found a user by email but user ID was set to a different ID."); user = null; } } } if (user == null) { log.info("Tried to get info for " + loggedInUserId + " but no entry was found."); if (createIfMissing) { log.info("Creating new UserInfo for user: " + loggedInUserId); user = new UserInfo(); user.setUserId(loggedInUserId); user.setCurrentEmail(currentEmail); pm.makePersistent(user); } } return user; } @SuppressWarnings("unchecked") private UserInfo queryAndReturnFirst(Query query, String param) { List<UserInfo> users = (List<UserInfo>) query.execute(param); if (users.size() > 0) { return users.get(0); } return null; } /** * Loads a project. This isn't done using ProjectServiceImpl because it would create a circular * dependency. * * @param id projectId to load. * @return the loaded project. */ private Project getProject(long id) { // TODO(jimr): To reduce this code duplication, project loading should be done at a lower level // so that object can be injected both here and into project service. log.info("Getting project: " + Long.toString(id)); PersistenceManager pm = pmf.getPersistenceManager(); try { return pm.getObjectById(Project.class, id); } finally { pm.close(); } } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; /** * Server service for accessing user details or permissions. * * @author jimr@google.com (Jim Reardon) */ public interface UserService { public boolean isUserLoggedIn(); public boolean isInternalUser(); public String getEmail(); public LoginStatus getLoginStatus(String returnUrl); public boolean isWhitelistingEnabled(); public boolean isWhitelisted(); public boolean isDevMode(); public ProjectAccess getAccessLevel(long projectId); public ProjectAccess getAccessLevel(Project project); public ProjectAccess getAccessLevel(long projectId, String asEmail); public boolean hasAdministratorAccess(); public boolean hasViewAccess(long projectId); public boolean hasViewAccess(Project project); public boolean hasEditAccess(long projectId); public boolean hasEditAccess(Project project); public boolean hasEditAccess(long projectId, String asEmail); public boolean hasOwnerAccess(long projectId); public boolean hasAccess(ProjectAccess accessLevel, long project); public boolean hasAccess(ProjectAccess accessLevel, long project, String asEmail); public List<Long> getStarredProjects(); public void starProject(long projectId); public void unstarProject(long projectId); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; /** * Exception thrown when trying to access project information for which the current user does not * have sufficient permission. * * @author chrsmith@google.com (Chris Smith) */ public class InsufficientPrivlegesException extends RuntimeException { private final String message; public InsufficientPrivlegesException(String message) { this.message = message; } @Override public String getMessage() { return "Error: You do not have sufficient privleges. " + message; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc; import java.util.List; /** * Service allowing access to user / login data. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UserRpcImpl extends RemoteServiceServlet implements UserRpc { private final UserService userService; @Inject public UserRpcImpl(UserService userService) { this.userService = userService; } @Override public ProjectAccess getAccessLevel(long projectId) { return userService.getAccessLevel(projectId); } @Override public LoginStatus getLoginStatus(String returnUrl) { return userService.getLoginStatus(returnUrl); } @Override public List<Long> getStarredProjects() { return userService.getStarredProjects(); } @Override public boolean hasAdministratorAccess() { return userService.hasAdministratorAccess(); } @Override public boolean hasEditAccess(long projectId) { return userService.hasEditAccess(projectId); } @Override public boolean isDevMode() { return userService.isDevMode(); } @Override public void starProject(long projectId) { userService.starProject(projectId); } @Override public void unstarProject(long projectId) { userService.unstarProject(projectId); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpc; import java.util.List; /** * RPC methods that allow interaction with project data. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class ProjectRpcImpl extends RemoteServiceServlet implements ProjectRpc { private final ProjectService projectService; @Inject public ProjectRpcImpl(ProjectService projectService) { this.projectService = projectService; } @Override public Long createAttribute(Attribute attribute) { return projectService.createAttribute(attribute); } @Override public Capability createCapability(Capability capability) { return projectService.createCapability(capability); } @Override public Long createComponent(Component component) { return projectService.createComponent(component); } @Override public Long createProject(Project project) { return projectService.createProject(project); } @Override public Capability getCapabilityById(long projectId, long capabilityId) { return projectService.getCapabilityById(projectId, capabilityId); } @Override public List<AccLabel> getLabels(long projectId) { return projectService.getLabels(projectId); } @Override public List<Attribute> getProjectAttributes(long projectId) { return projectService.getProjectAttributes(projectId); } @Override public Project getProjectById(long projectId) { return projectService.getProjectById(projectId); } @Override public List<Capability> getProjectCapabilities(long projectId) { return projectService.getProjectCapabilities(projectId); } @Override public List<Component> getProjectComponents(long projectId) { return projectService.getProjectComponents(projectId); } @Override public List<Project> query(String query) { return projectService.query(query); } @Override public List<Project> queryUserProjects() { return projectService.queryUserProjects(); } @Override public void removeAttribute(Attribute attribute) { projectService.removeAttribute(attribute); } @Override public void removeCapability(Capability capability) { projectService.removeCapability(capability); } @Override public void removeComponent(Component component) { projectService.removeComponent(component); } @Override public void removeProject(Project project) { projectService.removeProject(project); } @Override public void reorderAttributes(long projectId, List<Long> newOrder) { projectService.reorderAttributes(projectId, newOrder); } @Override public void reorderCapabilities(long projectId, List<Long> newOrder) { projectService.reorderCapabilities(projectId, newOrder); } @Override public void reorderComponents(long projectId, List<Long> newOrder) { projectService.reorderComponents(projectId, newOrder); } @Override public Attribute updateAttribute(Attribute attribute) { return projectService.updateAttribute(attribute); } @Override public void updateCapability(Capability capability) { projectService.updateCapability(capability); } @Override public Component updateComponent(Component component) { return projectService.updateComponent(component); } @Override public void updateProject(Project project) { projectService.updateProject(project); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.common.collect.Lists; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.FailureRate; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.model.UserImpact; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.rpc.TestProjectCreatorRpc; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * A simple servlet that allows an admin to create a test project populated with some data. * Useful for testing purposes and to make sure everything is working how it should. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class TestProjectCreatorRpcImpl extends RemoteServiceServlet implements TestProjectCreatorRpc { private static final Logger LOG = Logger.getLogger(TestProjectCreatorRpcImpl.class.getName()); private final ProjectService projectService; private final UserService userService; private final DataService dataService; private final PersistenceManagerFactory pmf; @Inject public TestProjectCreatorRpcImpl(ProjectService projectService, UserService userService, DataService dataService, PersistenceManagerFactory pmf) { this.projectService = projectService; this.userService = userService; this.dataService = dataService; this.pmf = pmf; } @SuppressWarnings("unchecked") @Override public void createStandardDataSources() { LOG.info("Injecting standard datasources."); boolean admin = userService.hasAdministratorAccess(); boolean devMode = userService.isDevMode(); ServletUtils.requireAccess(admin || devMode); DataSource bugSource = new DataSource(); bugSource.setInternalOnly(true); bugSource.setName("Bug Database"); bugSource.setParameters(Lists.newArrayList("Path", "Hotlist")); DataSource testManager = new DataSource(); testManager.setInternalOnly(true); testManager.setName("Test Database"); testManager.setParameters(Lists.newArrayList("Label", "ProjectID", "SavedSearchID")); DataSource perforce = new DataSource(); perforce.setInternalOnly(true); perforce.setName("Perforce"); perforce.setParameters(Lists.newArrayList("Path")); DataSource issueTracker = new DataSource(); issueTracker.setInternalOnly(false); issueTracker.setName("Issue Tracker"); issueTracker.setParameters(Lists.newArrayList("Project", "Label", "Owner")); DataSource other = new DataSource(); other.setInternalOnly(false); other.setName("Other..."); other.setParameters(new ArrayList<String>()); List<DataSource> all = Lists.newArrayList( bugSource, testManager, perforce, issueTracker, other); PersistenceManager pm = pmf.getPersistenceManager(); try { // Remove any data source from what we will persist if it already exists. DataSource source; Iterator<DataSource> i = all.iterator(); while (i.hasNext()) { source = i.next(); Query query = pm.newQuery(DataSource.class); query.declareParameters("String nameParam"); query.setFilter("name == nameParam"); if (((List<DataSource>) query.execute(source.getName())).size() > 0) { i.remove(); } } pm.makePersistentAll(all); } finally { pm.close(); } } @Override public Project createTestProject() { LOG.info("Starting to create a sample project..."); boolean admin = userService.hasAdministratorAccess(); boolean devMode = userService.isDevMode(); ServletUtils.requireAccess(admin || devMode); // Project. LOG.info("Creating project."); Project project = new Project(); String testDescription = "An example project created by TestProjectCreator."; project.setDescription(testDescription); project.setName("Test Project " + System.currentTimeMillis()); Long projectId = projectService.createProject(project); // Attributes. LOG.info("Creating attributes."); List<Attribute> attributes = Lists.newArrayList(); Attribute attr1 = new Attribute(); attr1.setParentProjectId(projectId); attr1.setName("Fast"); attr1.setDescription("This should be speedy."); attr1.addLabel("owner: alaska@example"); attr1.addLabel("pm: will@example"); attr1.setAttributeId(projectService.createAttribute(attr1)); attributes.add(attr1); Attribute attr2 = new Attribute(); attr2.setParentProjectId(projectId); attr2.setName("Simple"); attr2.addLabel("owner: alaska@example"); attr2.setAttributeId(projectService.createAttribute(attr2)); attributes.add(attr2); Attribute attr3 = new Attribute(); attr3.setParentProjectId(projectId); attr3.setName("Secure"); attr3.addLabel("owner: margo@example"); attr3.addLabel("tester: quentin@example"); attr3.setAttributeId(projectService.createAttribute(attr3)); attributes.add(attr3); // Components. LOG.info("Creating components."); ArrayList<Component> components = Lists.newArrayList(); Component comp1 = new Component(projectId); comp1.setName("Shopping Cart"); comp1.addLabel("dev lead: miles@example"); comp1.addLabel("tester: katherine@example"); comp1.setDescription("Contains items people want to buy."); comp1.setComponentId(projectService.createComponent(comp1)); components.add(comp1); Component comp2 = new Component(projectId); comp2.setName("Sales Channel"); comp2.addLabel("dev lead: colin@example"); comp2.setComponentId(projectService.createComponent(comp2)); components.add(comp2); Component comp3 = new Component(projectId); comp3.setName("Social"); comp3.addLabel("owner: alaska@example"); comp3.setComponentId(projectService.createComponent(comp3)); components.add(comp3); Component comp4 = new Component(projectId); comp4.setName("Search"); comp4.setComponentId(projectService.createComponent(comp4)); components.add(comp4); // Capabilities. LOG.info("Creating capabilities."); ArrayList<Capability> capabilities = Lists.newArrayList(); Capability capa1 = new Capability( projectId, attributes.get(0).getAttributeId(), components.get(1).getComponentId()); capa1.setName("Credit card processing takes less than 5 seconds"); capa1.setFailureRate(FailureRate.OFTEN); capa1.addLabel("external"); capa1.addLabel("load test"); capa1.setDescription("Order is completed from clicking 'ORDER NOW' to success page."); capa1.setUserImpact(UserImpact.MINIMAL); capa1.setCapabilityId(projectService.createCapability(capa1).getCapabilityId()); capabilities.add(capa1); Capability capa2 = new Capability( projectId, attributes.get(0).getAttributeId(), components.get(1).getComponentId()); capa2.setName("Saved addresses and credit cards appear quickly"); capa2.setFailureRate(FailureRate.OCCASIONALLY); capa2.setUserImpact(UserImpact.MAXIMAL); capa2.setCapabilityId(projectService.createCapability(capa2).getCapabilityId()); capabilities.add(capa2); Capability capa3 = new Capability( projectId, attributes.get(2).getAttributeId(), components.get(1).getComponentId()); capa3.setName("All traffic is sent over https"); capa3.addLabel("ssl"); capa3.setFailureRate(FailureRate.NA); capa3.setUserImpact(UserImpact.MAXIMAL); capa3.setCapabilityId(projectService.createCapability(capa3).getCapabilityId()); capabilities.add(capa3); Capability capa4 = new Capability( projectId, attributes.get(2).getAttributeId(), components.get(3).getComponentId()); capa4.setName("Items removed from inventory do not appear in search"); capa4.setFailureRate(FailureRate.VERY_RARELY); capa4.setUserImpact(UserImpact.NA); capa4.setCapabilityId(projectService.createCapability(capa4).getCapabilityId()); capabilities.add(capa4); // Bugs. LOG.info("Creating bugs."); List<Bug> bugs = Lists.newArrayList(); Bug bug1 = new Bug(); bug1.setExternalId(42L); bug1.setTitle("SSL certificate error in some browsers."); bug1.addBugGroup("security"); bug1.addBugGroup("checkout"); bug1.setParentProjectId(projectId); bug1.setPriority(1L); bug1.setSeverity(2L); bug1.setState("Open"); bug1.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug1.setStateDate(System.currentTimeMillis() - (84000000 * 4)); bug1.setBugUrl("http://example/42"); dataService.addBug(bug1); bugs.add(bug1); Bug bug2 = new Bug(); bug2.setExternalId(123L); bug2.setTitle("+1 button is not showing on products with prime number IDs."); bug2.addBugGroup("social"); bug2.addBugGroup("browsing"); bug2.setParentProjectId(projectId); bug2.setPriority(1L); bug2.setSeverity(2L); bug2.setState("Open"); bug2.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug2.setStateDate(System.currentTimeMillis() - (84000000 * 2)); bug2.setBugUrl("http://example/123"); dataService.addBug(bug2); bugs.add(bug2); Bug bug3 = new Bug(); bug3.setExternalId(122L); bug3.setTitle("Search results always return developer's favorite item"); bug3.addBugGroup("search"); bug3.addBugGroup("accuracy"); bug3.setParentProjectId(projectId); bug3.setPriority(4L); bug3.setSeverity(4L); bug3.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug3.setState("Closed"); bug3.setStateDate(System.currentTimeMillis() - (84000000 * 10)); bug3.setBugUrl("http://example/34121"); dataService.addBug(bug3); bugs.add(bug3); // Checkins. LOG.info("Creating checkins."); Checkin checkin1 = new Checkin(); checkin1.setChangeUrl("http://example/code/16358580"); checkin1.setExternalId(16358580L); checkin1.addDirectoryTouched("java/com/example/DoorKnobFactoryFactory"); checkin1.setParentProjectId(projectId); checkin1.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); checkin1.setStateDate(System.currentTimeMillis() - (84000000 * 2)); checkin1.setSummary("Add factory to create a factory to provide Door Knob objects."); dataService.addCheckin(checkin1); Checkin checkin2 = new Checkin(); checkin2.setChangeUrl("http://example/code/16358581"); checkin2.setExternalId(16358581L); checkin2.addDirectoryTouched("java/com/example/Search"); checkin2.setParentProjectId(projectId); checkin2.setStateDate(System.currentTimeMillis() - (84000000 * 7)); checkin2.setSummary("Search engine optimizations"); dataService.addCheckin(checkin2); // Tests. LOG.info("Creating tests."); TestCase testcase1 = new TestCase(); testcase1.setParentProjectId(projectId); testcase1.setExternalId(1042L); testcase1.setTestCaseUrl("http://example/test/1042"); testcase1.setTitle("Search for 'dogfood'"); testcase1.setTargetAttributeId(attributes.get(1).getAttributeId()); testcase1.setTargetComponentId(components.get(1).getComponentId()); dataService.addTestCase(testcase1); TestCase testcase2 = new TestCase(); testcase2.setParentProjectId(projectId); testcase2.setExternalId(1043L); testcase2.setTestCaseUrl("http://example/test/1043"); testcase2.setTitle("Post an item to your favorite social network via sharing functions"); testcase2.setTargetCapabilityId(capabilities.get(3).getCapabilityId()); dataService.addTestCase(testcase2); for (int i = 0; i < 6; i++) { TestCase testcase3 = new TestCase(); testcase3.setParentProjectId(projectId); testcase3.setExternalId(Long.valueOf(1044 + i * 100)); testcase3.setTestCaseUrl("http://example/test/" + i); testcase3.setTitle("Some Random Automated Test " + i); testcase3.setState("Passed"); testcase3.setStateDate(System.currentTimeMillis() - (84000000L * i)); testcase3.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase3); } for (int i = 0; i < 4; i++) { TestCase testcase4 = new TestCase(); testcase4.setParentProjectId(projectId); testcase4.setExternalId(Long.valueOf(1045 + i * 100)); testcase4.setTestCaseUrl("http://example/test/" + i); testcase4.setTitle("Some Random Manual Test " + i); testcase4.setState("Failed"); testcase4.setStateDate(System.currentTimeMillis() - (84000000L * i)); testcase4.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase4); } for (int i = 0; i < 2; i++) { TestCase testcase5 = new TestCase(); testcase5.setParentProjectId(projectId); testcase5.setExternalId(Long.valueOf(1046 + i * 100)); testcase5.setTestCaseUrl("http://example/test/" + i); testcase5.setTitle("Test We Never Run " + i); testcase5.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase5); } LOG.info("Done. Returning created project."); return project; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import java.util.List; /** * RPC by which data details are retrieved or updated. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class DataRpcImpl extends RemoteServiceServlet implements DataRpc { private final DataService dataService; @Inject public DataRpcImpl(DataService dataService) { this.dataService = dataService; } @Override public void addBug(Bug bug) { dataService.addBug(bug); } @Override public void addCheckin(Checkin checkin) { dataService.addCheckin(checkin); } @Override public long addDataRequest(DataRequest request) { return dataService.addDataRequest(request); } @Override public long addFilter(Filter filter) { return dataService.addFilter(filter); } @Override public void addTestCase(TestCase testCase) { dataService.addTestCase(testCase); } @Override public List<DataSource> getDataSources() { return dataService.getDataSources(); } @Override public List<Filter> getFilters(long projectId) { return dataService.getFilters(projectId); } @Override public List<Bug> getProjectBugsById(long projectId) { return dataService.getProjectBugsById(projectId); } @Override public List<Checkin> getProjectCheckinsById(long projectId) { return dataService.getProjectCheckinsById(projectId); } @Override public List<DataRequest> getProjectRequests(long projectId) { return dataService.getProjectRequests(projectId); } @Override public List<TestCase> getProjectTestCasesById(long projectId) { return dataService.getProjectTestCasesById(projectId); } @Override public List<Signoff> getSignoffsByType(Long projectId, AccElementType type) { return dataService.getSignoffsByType(projectId, type); } @Override public Boolean isSignedOff(AccElementType type, Long elementId) { return dataService.isSignedOff(type, elementId); } @Override public void removeDataRequest(DataRequest request) { dataService.removeDataRequest(request); } @Override public void removeFilter(Filter filter) { dataService.removeFilter(filter); } @Override public void setSignedOff( Long projectId, AccElementType type, Long elementId, boolean isSignedOff) { dataService.setSignedOff(projectId, type, elementId, isSignedOff); } @Override public void updateBugAssociations( long bugId, long attributeId, long componentId, long capabilityId) { dataService.updateBugAssociations(bugId, attributeId, componentId, capabilityId); } @Override public void updateCheckinAssociations( long bugId, long attributeId, long componentId, long capabilityId) { dataService.updateCheckinAssociations(bugId, attributeId, componentId, capabilityId); } @Override public void updateDataRequest(DataRequest request) { dataService.updateDataRequest(request); } @Override public void updateFilter(Filter filter) { dataService.updateFilter(filter); } @Override public void updateTestAssociations( long testCaseId, long attributeId, long componentId, long capabilityId) { dataService.updateTestAssociations(testCaseId, attributeId, componentId, capabilityId); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.servlet.RequestScoped; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.service.impl.DataServiceImpl; import com.google.testing.testify.risk.frontend.server.service.impl.ProjectServiceImpl; import com.google.testing.testify.risk.frontend.server.service.impl.UserServiceImpl; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; /** * Sets up injectable classes for Guice. Items listed here can be injected into the constructors * of servlets. * * @author jimr@google.com (Jim Reardon) */ public class GuiceProviderModule extends AbstractModule { @Provides @RequestScoped @Inject PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf) { return pmf.getPersistenceManager(); } @Provides @Singleton PersistenceManagerFactory getPersistenceManagerFactory() { return JDOHelper.getPersistenceManagerFactory("transactions-optional"); } @Override protected void configure() { bind(DataService.class).to(DataServiceImpl.class); bind(ProjectService.class).to(ProjectServiceImpl.class); bind(UserService.class).to(UserServiceImpl.class); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.task; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This task processes a individual item to be uploaded (ie, one bug or one test) and inserts * it into the data store. * * The expected data are: * - json (the json of ONE data item: bug, test, checkin) * - user (the user to insert on behalf of) * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UploadDataTask extends HttpServlet { private static final Logger LOG = Logger.getLogger(UploadDataTask.class.getName()); public static final String QUEUE = "dataupload"; public static final String URL = "/_tasks/upload"; private final DataService dataService; @Inject public UploadDataTask(DataService dataService) { this.dataService = dataService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LOG.info("TestCaseUploadTask::GET called, returning unsupported exception."); error(resp, "<h1>GET is unsupported</h1>\nTo upload test cases, use POST."); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String user = req.getParameter("user"); String jsonString = req.getParameter("json"); try { // TODO(jimr): add impersonation of user in string user. JSONObject json = new JSONObject(jsonString); JSONObject item; if (json.has("bug")) { item = json.getJSONObject("bug"); Bug bug = new Bug(); bug.setParentProjectId(item.getLong("projectId")); bug.setExternalId(item.getLong("bugId")); bug.setTitle(item.getString("title")); bug.setPath(item.getString("path")); bug.setSeverity(item.getLong("severity")); bug.setPriority(item.getLong("priority")); bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups")))); bug.setBugUrl(item.getString("url")); bug.setState(item.getString("status")); bug.setStateDate(item.getLong("statusDate")); dataService.addBug(bug); } else if (json.has("test")) { item = json.getJSONObject("test"); TestCase test = new TestCase(); test.setParentProjectId(item.getLong("projectId")); test.setExternalId(item.getLong("testId")); test.setTitle(item.getString("title")); test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags")))); test.setTestCaseUrl(item.getString("url")); test.setState(item.getString("result")); test.setStateDate(item.getLong("resultDate")); dataService.addTestCase(test); } else if (json.has("checkin")) { item = json.getJSONObject("checkin"); Checkin checkin = new Checkin(); checkin.setParentProjectId(item.getLong("projectId")); checkin.setExternalId(item.getLong("checkinId")); checkin.setSummary(item.getString("summary")); checkin.setDirectoriesTouched( Sets.newHashSet(StringUtil.csvToList(item.getString("directories")))); checkin.setChangeUrl(item.getString("url")); checkin.setState(item.getString("state")); checkin.setStateDate(item.getLong("stateDate")); dataService.addCheckin(checkin); } else { LOG.severe("No applicable data found for json: " + json.toString()); } } catch (JSONException e) { // We don't issue a 500 or similar response code here to prevent retries, which would have // no different a result. LOG.severe("Couldn't parse input JSON: " + jsonString); return; } } private void error(HttpServletResponse resp, String errorText) throws IOException { resp.getOutputStream().print(errorText); resp.sendError(500); return; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.filter; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.server.service.UserService; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Filters access to the application based off the whitelist field in a UserInfo object. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class WhitelistFilter implements Filter { private static final Logger log = Logger.getLogger(WhitelistFilter.class.getName()); private final UserService userService; @Inject public WhitelistFilter(UserService userService) { this.userService = userService; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; if (userService.isWhitelistingEnabled() && !userService.isWhitelisted()) { String email = userService.getEmail(); if (email == null) { email = "(null)"; } log.warning("User not whitelisted tried to access server: " + email); httpResponse.getWriter().write("404 Not Found"); httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig arg0) { } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.api.impl; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.DataRequestDocumentGenerator; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet for exposing project data requests to third party tools, so that those requests may be * fulfilled. * * @author chrsmith@google.com (Chris Smith) */ @Singleton public class DataApiImpl extends HttpServlet { private static final Logger log = Logger.getLogger(DataApiImpl.class.getName()); private final DataService dataService; private final ProjectService projectService; private final UserService userService; @Inject public DataApiImpl(DataService dataService, ProjectService projectService, UserService userService) { this.dataService = dataService; this.projectService = projectService; this.userService = userService; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("DataRequestServlet::GET"); if (!userService.isUserLoggedIn()) { resp.getWriter().print("You must be logged in to access this service."); resp.sendError(5000); return; } // Query all projects the current user (typically a role account) has EDIT access to. List<Project> projectsUserCanEdit = projectService.queryProjectsUserHasEditAccessTo(); // Query all data requests for those projects. List<DataRequest> relevantDataRequests = Lists.newArrayList(); for (Project project : projectsUserCanEdit) { relevantDataRequests.addAll(dataService.getProjectRequests(project.getProjectId())); } // Generate the XML document and serve. String xmlDocumentText = DataRequestDocumentGenerator.generateDocument(relevantDataRequests); resp.getWriter().write(xmlDocumentText); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("DataRequestServlet::POST"); resp.getWriter().write("Please call this URL using GET."); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.api.impl; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.task.UploadDataTask; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This servlet accepts user data (JSON encoded) and passes it off to a task which does the actual * processing. {@link UploadDataTask} * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UploadApiImpl extends HttpServlet { private static final Logger LOG = Logger.getLogger(UploadApiImpl.class.getName()); private final UserService userService; @Inject public UploadApiImpl(UserService userService) { this.userService = userService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LOG.info("UploadDataServlet::GET called, returning unsupported exception."); error(resp, "<h1>GET is unsupported</h1>\nTo upload data, use POST."); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { BufferedReader reader = req.getReader(); StringBuilder input = new StringBuilder(); while (reader.ready()) { input.append(req.getReader().readLine()); } LOG.info("Input received: " + input.toString()); JSONArray json; try { json = new JSONArray(input.toString()); } catch (JSONException e) { LOG.warning("Couldn't parse JSON: " + e.toString()); error(resp, "Malformed JSON could not be parsed: " + e.toString()); return; } LOG.info("JSON received: " + json.toString()); JSONObject o; TaskOptions task; String email = userService.getEmail(); for (int i = 0; i < json.length(); i++) { try { o = json.getJSONObject(i); task = TaskOptions.Builder.withUrl(UploadDataTask.URL).method(Method.POST) .param("json", o.toString()) .param("user", email); ServletUtils.queueWithRetries(UploadDataTask.QUEUE, task, "Processing data item upload"); } catch (JSONException e) { LOG.warning("Couldn't parse item " + i + " in JSON array: " + e.toString()); resp.getOutputStream().print("<p>Couldn't parse item " + i + "</p>\n"); } } } private void error(HttpServletResponse resp, String errorText) throws IOException { resp.getOutputStream().print(errorText); resp.sendError(500); return; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.util; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.appengine.api.utils.SystemProperty; import com.google.testing.testify.risk.frontend.server.InsufficientPrivlegesException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * Utility methods for servlets. * * @author jimr@google.com (Jim Reardon) */ public class ServletUtils { private static final String URL = System.getProperty("com.google.testing.testify.risk.frontend.url"); private static final Logger LOG = Logger.getLogger(ServletUtils.class.getName()); private static final int QUEUE_RETRIES = 10; private ServletUtils() {} // COV_NF_LINE /** * Throws an access exception if user doesn't have access to do the operation. EG: * ServerletUtils.requireAccess(userService.hasAccess(...)). * * @param hasAccess */ public static void requireAccess(boolean hasAccess) { // TODO(jimr): It'd be nice if this was less clunky. Figure out a way to do that. if (!hasAccess) { throw new InsufficientPrivlegesException("You don't have access to perform that action."); } } /** * Lists returned from GAE's PersistanceManager are a private type which cannot be marshalled to * client-side GWT code. This method simply copies elements from whatever input List<T> into a * GWT-friendly detached ArrayList<T>. * * @param inputList the list to safenize. * @param pm the persistence manager. This is needed in order to create a detached copy. * @return a copied, serialization-safe list. */ public static <T> List<T> makeGwtSafe(List<T> inputList, PersistenceManager pm) { List<T> copiedList = new ArrayList<T>(inputList.size()); for (T item : inputList) { copiedList.add(pm.detachCopy(item)); } return copiedList; } /** * Lists returned from GAE's PersistanceManager are a private type which cannot be marshalled to * client-side GWT code. This method simply copies elements from whatever input <T> into a * GWT-friendly detached <T>. * * @param input the item to safenize. * @param pm the persistence manager. This is needed in order to create a detached copy. * @return a copied, serialization-safe item. */ public static <T> T makeGwtSafe(T input, PersistenceManager pm) { return pm.detachCopy(input); } public static boolean queueWithRetries(String queueName, TaskOptions task, String description) { Queue queue = QueueFactory.getQueue(queueName); for (int i = 0; i < QUEUE_RETRIES; i++) { try { queue.add(task); return true; } catch (TransientFailureException e) { LOG.warning("Retrying queue add for task due to queue failure: " + description); } } LOG.severe("Could not enqueue task after " + QUEUE_RETRIES + "retries: " + description); return false; } public static void notifyRemovedAccess(String from, List<String> emails, String accessType, String project, String projectId) { notifyAccessChanged(from, emails, accessType, project, projectId, false); } public static void notifyAddedAccess(String from, List<String> emails, String accessType, String project, String projectId) { notifyAccessChanged(from, emails, accessType, project, projectId, true); } private static void notifyAccessChanged(String from, List<String> emails, String accessType, String project, String projectId, boolean isAdded) { LOG.info("Trying to message users about change in " + accessType + " access."); if (emails.size() < 1) { LOG.warning("No emails specified to notify."); return; } try { String url = URL + "/#/" + projectId +"/project-settings"; String verb = isAdded ? "added" : "removed"; String change = "You have been " + verb + " as an " + accessType + " of Test Analytics Project: " + project; Session session = Session.getDefaultInstance(new Properties(), null); for (String email : emails) { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from, "Test Analytics on behalf of " + from)); LOG.info("Sending email to " + email + "(" + change + ")"); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); msg.setSubject(change); msg.setText(change + "\n\nThis Test Analytics project's URL:\n\n" + url + "\n\nIf you believe this was a mistake, contact " + from + " who made the change."); if (SystemProperty.environment.value().equals( SystemProperty.Environment.Value.Production)) { Transport.send(msg); } else { LOG.info("Not actually sending email; not in production environment."); } } } catch (UnsupportedEncodingException e) { // COV_NF_START LOG.severe("Couldn't send email."); } catch (AddressException e) { LOG.severe("Couldn't send email."); } catch (MessagingException e) { LOG.severe("Couldn't send email."); } // COV_NF_END } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.util; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataRequestOption; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.StringWriter; import java.util.Collection; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Generates an XML document for external data collectors. * * @author chrsmith@google.com (Chris Smith) */ public class DataRequestDocumentGenerator { private DataRequestDocumentGenerator() {} // COV_NF_LINE /** * Returns an XML document describing the data requests. */ public static String generateDocument(List<DataRequest> allDataRequests) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); Element documentRoot = document.createElement("TestAnalytics"); document.appendChild(documentRoot); // Group all requests by their parent project. Multimap<Long, DataRequest> requestsByProject = getRequestsByProject(allDataRequests); for (Long projectId : requestsByProject.keySet()) { Element projectElement = document.createElement("DataRequests"); projectElement.setAttribute("ProjectID", Long.toString(projectId)); documentRoot.appendChild(projectElement); // Group project requests by data source. Collection<DataRequest> projectRequests = requestsByProject.get(projectId); Multimap<String, DataRequest> requestsBySource = getRequestsByDataSource(projectRequests); for (String sourceName : requestsBySource.keySet()) { Element dataSourceElement = document.createElement("DataRequest"); dataSourceElement.setAttribute("Type", sourceName); projectElement.appendChild(dataSourceElement); // Write out the configuration parameter strings for the data source. for (DataRequest request : requestsBySource.get(sourceName)) { for (DataRequestOption option : request.getDataRequestOptions()) { Element dataSourceParameter = document.createElement("Parameter"); dataSourceParameter.setAttribute("Name", option.getName()); dataSourceParameter.appendChild(document.createTextNode(option.getValue())); dataSourceElement.appendChild(dataSourceParameter); } } } } // Now dump the document in memory to a string. Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new javax.xml.transform.stream.StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); // COV_NF_START } catch (TransformerConfigurationException tce) { return "Error in transformer configuration."; } catch (TransformerException te) { return "Error transforming document."; } catch (ParserConfigurationException pce) { return "Error in parser configuration."; } // COV_NF_END } private static Multimap<Long, DataRequest> getRequestsByProject( Collection<DataRequest> requests) { Multimap<Long, DataRequest> requestsByProject = HashMultimap.create(); for (DataRequest request : requests) { requestsByProject.put(request.getParentProjectId(), request); } return requestsByProject; } private static Multimap<String, DataRequest> getRequestsByDataSource( Collection<DataRequest> requests) { Multimap<String, DataRequest> requestsBySource = HashMultimap.create(); for (DataRequest request : requests) { requestsBySource.put(request.getDataSourceName(), request); } return requestsBySource; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for a Label. Labels can be assigned to any part of an ACC model. * A label is stored as a two-state label (essentially, a name and value pair). This can * represent things like: * "Priority-P4" where P4 is the value to the name Priority. * * For labels where there is not a name/value structure, the label is simply stored as the name. * "Security", for example, would have an empty value and the entire label text in name. * * The entire label is not stored as one text field, but can be generated by this class using * the function getLabelText(). This function should be used instead of doing this manually. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class AccLabel implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private Long projectId; @Persistent private AccElementType elementType; @Persistent private Long elementId; @Persistent private String name; @Persistent private String value; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public AccElementType getElementType() { return elementType; } public void setElementType(AccElementType elementType) { this.elementType = elementType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } /** * Will attempt to split a label into its name / value pair, or set it all as name if it is not * a two-state label. */ public void setLabelText(String labelText) { if (labelText == null) { name = null; value = null; } else { String[] split = labelText.split("-", 2); if (split.length > 0) { name = split[0]; if (split.length > 1) { value = split[1]; } } } } /** * Returns a combined label with the name and value in one string. Eg: * name=Priority value=P4 would become "Priority-P4". * name=Security value=null would become "Security". * @return the combined label. */ public String getLabelText() { String labelText = name; if (value != null) { labelText += "-" + value; } return labelText; } public void setElementId(Long elementId) { this.elementId = elementId; } public Long getElementId() { return elementId; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a bug or defect in a piece of software. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class Bug implements Serializable, UploadedDatum { /** Unique identifier to store the bug in App Engine. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the bug belongs to. */ @Persistent private Long parentProjectId; /** * Bug ID provided by the data provider. Must be unique across all bugs associated with this * project. */ @Persistent private Long externalId; /** Bug severity. Sev 1 - severe, Sev 4 - ignorable.*/ @Persistent private Long severity; /** Bug priority. Pri 1 - fix now, Pri 4 - puntable. */ @Persistent private Long priority; /** Arbitrary title of the bug. */ @Persistent private String title; /** Component path, or similar, of the bug. */ @Persistent private String path; /** State, eg: Closed, Open, Active, etc **/ @Persistent private String state; /** Date this bug was originally reported **/ @Persistent private Long stateDate; /** Attribute this bug should be associated with (if any). */ @Persistent private Long targetAttributeId; /** Component this bug should be associated with (if any). */ @Persistent private Long targetComponentId; /** Capability this bug should be associated with (if any). */ @Persistent private Long targetCapabilityId; /** * Bug group is a meta string to identify groups of bugs, typically for linking them to specific * components. For example, if the bug database is organized by component then the bug * group should be its path in the database. */ @Persistent private Set<String> groups = new HashSet<String>(); /** URL to identify view more information about the bug. */ @Persistent private String bugUrl; @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setInternalId(Long internalId) { this.internalId = internalId; } /** * @return the bug's internal ID, which is unique across all projects. */ @Override public Long getInternalId() { return internalId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } /** * @return an arbitrary ID associated with the bug. (The bug ID in an external bug database.) */ @Override public Long getExternalId() { return externalId; } public void setSeverity(Long severity) { this.severity = severity; } public Long getSeverity() { return severity; } public void setPriority(Long priority) { this.priority = priority; } public Long getPriority() { return priority; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public void addBugGroup(String groupName) { groups.add(groupName); } public void removeBugGroup(String groupName) { groups.remove(groupName); } public void setBugGroups(Set<String> bugGroups) { this.groups = bugGroups; } public Set<String> getBugGroups() { return groups; } /** * @return the group names associated with this bug as a comma separated list. */ public String getGroupsAsCommaSeparatedList() { return StringUtil.listToCsv(groups); } public void setBugUrl(String bugUrl) { this.bugUrl = bugUrl; } public String getBugUrl() { return bugUrl; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { return title; } @Override public String getLinkUrl() { return bugUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append("This bug is attached to the following groups: "); text.append(this.getGroupsAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return targetAttributeId != null; } @Override public boolean isAttachedToComponent() { return targetComponentId != null; } @Override public boolean isAttachedToCapability() { return targetCapabilityId != null; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public DatumType getDatumType() { return DatumType.BUGS; } @Override public String getField(String field) { if ("Title".equals(field)) { return title; } else if ("Path".equals(field)) { return path; } else if ("Labels".equals(field)) { return getGroupsAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.util.Collection; /** * Represents an Attribute x Component intersection for calculating risk. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ public class CapabilityIntersectionData { private final Attribute parentAttribute; private final Component parentComponent; private final Collection<Capability> cellCapabilities; public CapabilityIntersectionData( Attribute parentAttribute, Component parentComponent, Collection<Capability> cellCapabilities) { this.parentAttribute = parentAttribute; this.parentComponent = parentComponent; this.cellCapabilities = cellCapabilities; } public Attribute getParentAttribute() { return parentAttribute; } public Component getParentComponent() { return parentComponent; } /** Project Capabilities associated with the Attribute x Component. */ public Collection<Capability> getCapabilities() { return cellCapabilities; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for storing Project data. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Project implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long projectId; @Persistent private String name; /** * Full paragraph or page-length description of the project. */ @Persistent private String description; /** * This field controls whether or not the project is listed in public queries. */ @Persistent private Boolean isPubliclyVisible = false; /** * Email addresses of users with owner access. They can do anything editors can do as well as * delete the project.. */ @Persistent private List<String> projectOwners = new ArrayList<String>(); /** * Email addresses of users with editor access. They can add, edit, or update project data. */ @Persistent private List<String> projectEditors = new ArrayList<String>(); /** * Email addresses of users with view access. They can view but not edit project data. */ @Persistent private List<String> projectViewers = new ArrayList<String>(); /** * Allows the server-side to set the permissions so UI code has easy access without executing * an RPC. Server-side code should never rely on this value. */ @NotPersistent private ProjectAccess cachedAccessLevel; /** * Returns the Project's ID. Note that this will return null in the case the project hasn't been * persisted in the backing store (and doesn't have an ID yet). */ public Long getProjectId() { return projectId; } public void setProjectId(long projectId) { this.projectId = projectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setIsPubliclyVisible(Boolean isPubliclyVisible) { this.isPubliclyVisible = isPubliclyVisible; } public boolean getIsPubliclyVisible() { return isPubliclyVisible; } public void addProjectOwner(String ownerEmailAddress) { if (!projectOwners.contains(ownerEmailAddress)) { projectOwners.add(ownerEmailAddress); } } public void removeProjectOwner(String ownerEmailAddress) { projectOwners.remove(ownerEmailAddress); } public void setProjectOwners(List<String> projectOwners) { this.projectOwners = projectOwners; } public List<String> getProjectOwners() { return projectOwners; } public void addProjectEditor(String editorEmailAddress) { if (!projectEditors.contains(editorEmailAddress)) { projectEditors.add(editorEmailAddress); } } public void removeProjectEditor(String editorEmailAddress) { projectEditors.remove(editorEmailAddress); } public void setProjectEditors(List<String> projectEditors) { this.projectEditors = projectEditors; } public List<String> getProjectEditors() { return projectEditors; } public void addProjectView(String viewEmailAddress) { if (!projectViewers.contains(viewEmailAddress)) { projectViewers.add(viewEmailAddress); } } public void removeProjectViewer(String viewerEmailAddress) { projectViewers.remove(viewerEmailAddress); } public void setProjectViewers(List<String> projectViewers) { this.projectViewers = projectViewers; } public List<String> getProjectViewers() { return projectViewers; } public void setCachedAccessLevel(ProjectAccess cachedAccessLevel) { this.cachedAccessLevel = cachedAccessLevel; } public ProjectAccess getCachedAccessLevel() { return cachedAccessLevel; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a code checkin. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class Checkin implements Serializable, UploadedDatum { /** Unique identifier to store the checkin in App Engine. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the checkin belongs to. */ @Persistent private Long parentProjectId; /** * Checkin ID provided by the data provider. Must be unique across all checknis associated with * this project. */ @Persistent private Long externalId; @Persistent private String summary; /** * Directories where files were touched by this checkin. E.g., if files: * ADD alpha\beta\gamma\file1.txt * DELETE alpha\beta\gamma\file2.txt * EDIT alpha\beta\delta\file3.txt * * The set of directories would be { "alpha\beta\gamma", "alpha\beta\delta" }. */ @Persistent private Set<String> directoriesTouched = new HashSet<String>(); /** URL to identify view more information about the checkin. */ @Persistent private String changeUrl; /** Submitted, pending, etc. */ @Persistent private String state; /** Date it entered current state. */ @Persistent private Long stateDate; /** ID of the Attribute this checkin applies to, if any. */ @Persistent private Long targetAttributeId; /** ID of the Component this checkin applies to, if any. */ @Persistent private Long targetComponentId; /** ID of the Capability this checkin applies to, if any. */ @Persistent private Long targetCapabilityId; @Override public void setInternalId(Long internalId) { this.internalId = internalId; } @Override public Long getInternalId() { return internalId; } @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } @Override public Long getExternalId() { return externalId; } public void setSummary(String summary) { this.summary = summary; } public String getSummary() { return summary; } public void setDirectoriesTouched(Set<String> directoriesTouched) { this.directoriesTouched = directoriesTouched; } public Set<String> getDirectoriesTouched() { return directoriesTouched; } /** * @return the directories the checkin has touched as a comma separated list. */ public String getDirectoriesTouchedAsCommaSeparatedList() { return StringUtil.listToCsv(directoriesTouched); } public void addDirectoryTouched(String directory) { directoriesTouched.add(directory); } public void removeDirectoryTouched(String directory) { directoriesTouched.remove(directory); } public void setChangeUrl(String changeUrl) { this.changeUrl = changeUrl; } public String getChangeUrl() { return changeUrl; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { if (externalId == null) { return "Checkin (no id)"; } return ("Checkin #" + Long.toString(externalId)); } @Override public String getLinkUrl() { return changeUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append(summary); text.append("The following directories were touched: "); text.append(getDirectoriesTouchedAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return getTargetAttributeId() != null; } @Override public boolean isAttachedToCapability() { return getTargetCapabilityId() != null; } @Override public boolean isAttachedToComponent() { return getTargetComponentId() != null; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public DatumType getDatumType() { return DatumType.CHECKINS; } @Override public String getField(String field) { if ("Summary".equals(field)) { return summary; } else if ("Directories".equals(field)) { return getDirectoriesTouchedAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.util.List; /** * Supported data types. * * For each data type we keep track of how to refer to it in both a singular and plural sense. * We also track what parts of the datum support filtering. * * @author jimr@google.com (Jim Reardon) */ public enum DatumType { /** * Filtering is currently executed inside the {@link Filter} class. That, in turn, relies * upon each class that implements UploadedDatum to return any filterable field through the * <em>getField</em> method. */ BUGS("Bugs", "Bug", Lists.newArrayList("Title", "Path", "Labels")), TESTS("Tests", "Test", Lists.newArrayList("Title", "Labels")), CHECKINS("Checkins", "Checkin", Lists.newArrayList("Summary", "Directories")); private final String plural; private final String singular; private final List<String> filterTypes; DatumType(String plural, String singular, List<String> filterTypes) { this.plural = plural; this.singular = singular; this.filterTypes = filterTypes; } public String getPlural() { return plural; } public String getSingular() { return singular; } public List<String> getFilterTypes() { return filterTypes; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * An individual configuration option for a data request. For example, this is an example of * a data request option for a Bug * * name = "ComponentPath" * value = "\Testing\Tools\Test Analytics" * * This would import any bug under that component path. * * or * * name = "Hotlist" * value = "123123" * * This would import the bugs in hotlist 123123. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class DataRequestOption implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private String name; @Persistent private String value; @Persistent private DataRequest dataRequest; public DataRequestOption() { } public DataRequestOption(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getId() { return id; } public void setId(String id) { this.id = id; } public DataRequest getDataRequest() { return dataRequest; } public void setDataRequest(DataRequest dataRequest) { this.dataRequest = dataRequest; } }
Java
package com.google.testing.testify.risk.frontend.model; import java.util.List; /** * Interface that defines some commonality between items that have labels. For use in making * some functions generic. * * @author jimr@google.com (Jim Reardon) */ public interface HasLabels { public Long getId(); public long getParentProjectId(); public void setAccLabels(List<AccLabel> labels); public void addLabel(AccLabel label); public List<AccLabel> getAccLabels(); public AccElementType getElementType(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Capability. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Capability implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.CAPABILITY; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long capabilityId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); /** Parent Component. */ @Persistent private long componentId; /** Parent Attribute. */ @Persistent private long attributeId; @Persistent private FailureRate failureRate = FailureRate.NA; @Persistent private UserImpact userImpact = UserImpact.NA; @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); public Capability() { } /** * Constructs a new Capability. * * @param parentProjectId ID of the owning Project. * @param parentAttributeId Attribute ID of the parent Attribute. * @param parentComponentId Component ID of the parent Component. */ public Capability(long parentProjectId, long parentAttributeId, long parentComponentId) { this.parentProjectId = parentProjectId; this.componentId = parentComponentId; this.attributeId = parentAttributeId; } public Long getCapabilityId() { return capabilityId; } @Override public Long getId() { return getCapabilityId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } public void setCapabilityId(long capabilityId) { this.capabilityId = capabilityId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getComponentId() { return componentId; } public void setComponentId(long componentId) { this.componentId = componentId; } public long getAttributeId() { return attributeId; } public void setAttributeId(long attributeId) { this.attributeId = attributeId; } public UserImpact getUserImpact() { return userImpact; } public void setUserImpact(UserImpact userImpact) { this.userImpact = userImpact; } public FailureRate getFailureRate() { return failureRate; } public void setFailureRate(FailureRate failureRate) { this.failureRate = failureRate; } /** * @return the stable intersection key. {@See getCapabilityIntersectionKey} */ public int getCapabilityIntersectionKey() { return Capability.getCapabilityIntersectionKey(componentId, attributeId); } /** * Given a parent Component and Attribute return a random, but stable integer index. This * allows efficient lookup for Capabilities based on parent Components and Attribute pairs. * * @param component the parent component. * @param attribute the parent attribute. * @return a stable integer corresponding to the unique component / attribute pairing sutable * for placing Capability lists into a map. */ public static int getCapabilityIntersectionKey(Component component, Attribute attribute) { return Capability.getCapabilityIntersectionKey( component.getComponentId(), attribute.getAttributeId()); } /** * Computes a capability intersection key given the raw component and attribute IDs. */ private static int getCapabilityIntersectionKey(long componentId, long attributeId) { return Integer.valueOf((int) ((componentId << 16) ^ attributeId)); } public long getDisplayOrder() { return displayOrder; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public AccLabel addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(capabilityId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); return label; } public AccLabel addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(capabilityId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); return label; } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Represents an option for importing data and its options. For example, "Issue Tracker" would * be a DataSource and its parameters are options for search, such as "Owner". * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class DataSource implements Serializable { @SuppressWarnings("unused") @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String name; @Persistent private List<String> parameters; @Persistent private Boolean internalOnly; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setInternalOnly(Boolean internalOnly) { this.internalOnly = internalOnly; } public Boolean isInternalOnly() { return internalOnly; } public void setParameters(List<String> parameters) { this.parameters = parameters; } public List<String> getParameters() { return parameters; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Configuration object for gathering data from an external source. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class DataRequest implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long requestId; @Persistent private long parentProjectId; /** Name of the external data source. For example, "Google Code Bug Database". */ @Persistent private String dataSourceName; /** A custom name if this is, for example, the "Other..." box. */ @Persistent private String customName; /** * List of options for this data request. For example, an option might be: * Component Path -> { Project/Component/Path } */ @Persistent(mappedBy = "dataRequest", defaultFetchGroup = "true") private List<DataRequestOption> dataRequestOptions = Lists.newArrayList(); public void setRequestId(Long requestId) { this.requestId = requestId; } public Long getRequestId() { return requestId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public long getParentProjectId() { return parentProjectId; } public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; } public String getDataSourceName() { return dataSourceName; } public void setCustomName(String customName) { this.customName = customName; } public String getCustomName() { return customName; } public List<DataRequestOption> getDataRequestOptions() { return dataRequestOptions; } public void setDataRequestOptions(List<DataRequestOption> dataRequestOptions) { this.dataRequestOptions = dataRequestOptions; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * An individual option for a filter. For example, this is an example of a FilterOption that * could appear on a bug: * * type = "Title" * value = "[security]" * * This would match any bug that has [security] inside its title. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class FilterOption implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private String type; @Persistent private String value; @Persistent private Filter filter; public FilterOption() { } public FilterOption(String type, String value) { this.type = type; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; /** * Contains the status of the current user (logged in, logged out, email, et cetera). * * @author jimr@google.com (Jim Reardon) */ public class LoginStatus implements Serializable { private boolean isLoggedIn; private String url; private String email; public LoginStatus() { } /** Disable construction, see {@See LoggedInStatus} and {@See LoggedOutStatus}. */ public LoginStatus(boolean isLoggedIn, String url, String email) { this.isLoggedIn = isLoggedIn; this.url = url; this.email = email; } public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setIsLoggedIn(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; } public boolean getIsLoggedIn() { return isLoggedIn; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a testcase to mitigate risk in a piece of software. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class TestCase implements Serializable, UploadedDatum { /** Unique identifier for this test case. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the test case belongs to. */ @Persistent private Long parentProjectId; /** * Test case ID provided by the data provider. Must be unique across all bugs associated with this * project. */ @Persistent private Long externalId; /** Arbitrary title of the test case. */ @Persistent private String title; /** * Test cases have tags, which will be used to map it to Attributes, Components, Capabilities, * and so on. */ @Persistent private Set<String> tags = new HashSet<String>(); /** URL to identify view more information about the test case. */ @Persistent private String testCaseUrl; /** ID of the Attribute this testcase applies to, if any. */ @Persistent private Long targetAttributeId; /** ID of the Component this testcase applies to, if any. */ @Persistent private Long targetComponentId; /** ID of the Capability this testcase applies to, if any. */ @Persistent private Long targetCapabilityId; /** The status -- passed, failed, etc. */ @Persistent private String state; /** Result date. */ @Persistent private Long stateDate; @Override public void setInternalId(Long internalId) { this.internalId = internalId; } @Override public Long getInternalId() { return internalId; } @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } @Override public Long getExternalId() { return externalId; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public Set<String> getTags() { return tags; } public void setTags(Set<String> tags) { this.tags = tags; } public void removeTag(String tag) { tags.remove(tag); } public void addTag(String tag) { tags.add(tag); } /** * @return the tags associated with this test case as a comma separated list. */ public String getTagsAsCommaSeparatedList() { return StringUtil.listToCsv(tags); } public void setTestCaseUrl(String testCaseUrl) { this.testCaseUrl = testCaseUrl; } public String getTestCaseUrl() { return testCaseUrl; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { return title; } @Override public String getLinkUrl() { return testCaseUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append("Last Result: "); text.append(state == null ? "n/a" : state); text.append(" This testcase is labeled with the following tags: "); text.append(getTagsAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return getTargetAttributeId() != null; } @Override public boolean isAttachedToCapability() { return getTargetCapabilityId() != null; } @Override public boolean isAttachedToComponent() { return getTargetComponentId() != null; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public DatumType getDatumType() { return DatumType.TESTS; } @Override public String getField(String field) { if ("Title".equals(field)) { return title; } else if ("Labels".equals(field)) { return getTagsAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enumeration for storing potential failure rates. * * @author chrsmith@google.com (Chris Smith) */ public enum UserImpact { NA (-2, "n/a"), MINIMAL (0, "Minimal"), SOME (1, "Some"), CONSIDERABLE (2, "Considerable"), MAXIMAL (3, "Maximal"); final int ordinal; final String description; private UserImpact(int ordinal, String description) { this.ordinal = ordinal; this.description = description; } public int getOrdinal() { return ordinal; } public String getDescription() { return description; } /** * Convert UserImpact.getDescription() into the original UserImpact instance. Enum.getValue * cannot be used because that requires the "ALL_CAPS" form of the value, rather than * the "User Friendly" getName version. */ public static UserImpact fromDescription(String name) { for (UserImpact impact : UserImpact.values()) { if (impact.getDescription().equals(name)) { return impact; } } return null; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Stores a boolean that determines if a ACC member has been signed off upon. This could be a * boolean on the ACC directly, but likely we will start to store much more data here -- an * audit trail, etc, so this will start out as a very small class in expectation to grow. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Signoff implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private long parentProjectId; @Persistent private AccElementType elementType; @Persistent private Long elementId; @Persistent private Boolean signedOff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getParentProjectId() { return parentProjectId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public AccElementType getElementType() { return elementType; } public void setElementType(AccElementType elementType) { this.elementType = elementType; } public Long getElementId() { return elementId; } public void setElementId(Long elementId) { this.elementId = elementId; } public Boolean getSignedOff() { return signedOff; } public void setSignedOff(Boolean signedOff) { this.signedOff = signedOff; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enum that lists all the possible element types in an ACC model. * * @author jimr@google.com (Jim Reardon) */ public enum AccElementType { ATTRIBUTE("Attribute"), COMPONENT("Component"), CAPABILITY("Capability"); private String friendlyName; private AccElementType(String friendlyName) { this.friendlyName = friendlyName; } public String getFriendlyName() { return friendlyName; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Object for tracking user information. For example, starred/favorite projects. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class UserInfo implements Serializable { @SuppressWarnings("unused") @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; /** The User ID is the same ID returned by the App Engine UserService. */ @Persistent private String userId; /** * User's current email. This should not be keyed off of as the user's * email might change but still remain the same User ID. * * This can also be used to populate user id -- if user ID is null or missing, but email * is present, upon login the user ID will be populated. */ @Persistent private String currentEmail; /** * If a user is whitelisted, they will always have access to the application. Some users * will not require to be whitelisted, if they are permitted by default (ie, @google.com). */ @Persistent private Boolean isWhitelisted; /** List of IDs of starred projects. */ @Persistent private List<Long> starredProjects = Lists.newArrayList(); public void setUserId(String userId) { this.userId = userId; } public String getUserId() { return userId; } public void starProject(long projectId) { starredProjects.add(projectId); } public void unstarProject(long projectId) { starredProjects.remove(projectId); } public void setStarredProjects(List<Long> starredProjects) { this.starredProjects = starredProjects; } public List<Long> getStarredProjects() { return starredProjects; } public void setIsWhitelisted(boolean isWhitelisted) { this.isWhitelisted = isWhitelisted; } public Boolean getIsWhitelisted() { return isWhitelisted == null ? false : isWhitelisted; } public void setCurrentEmail(String currentEmail) { this.currentEmail = currentEmail; } public String getCurrentEmail() { return currentEmail; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import com.google.testing.testify.risk.frontend.model.DatumType; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * A representation of a filter to automatically assign data to ACC parts. * * A Filter will automatically assign data uploaded to specific ACC pieces. For example, * a Filter may say "assign any test labeled with 'Security' to the Security Attribute. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Filter implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private long parentProjectId; @Persistent private DatumType filterType; @Persistent private String filterConjunction; @Persistent(mappedBy = "filter", defaultFetchGroup = "true") private List<FilterOption> filterOptions = Lists.newArrayList(); @Persistent private Long targetAttributeId; @Persistent private Long targetComponentId; @Persistent private Long targetCapabilityId; /** * Creates a friendly title for this filter. * @return a title. */ public String getTitle() { return filterType.getSingular() + " Filter"; } public Long getId() { return id; } public void setId(long id) { this.id = id; } public long getParentProjectId() { return parentProjectId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public Long getTargetAttributeId() { return targetAttributeId; } public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } public Long getTargetComponentId() { return targetComponentId; } public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } public Long getTargetCapabilityId() { return targetCapabilityId; } public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } public DatumType getFilterType() { return filterType; } public void setFilterType(DatumType filterType) { this.filterType = filterType; } public List<FilterOption> getFilterOptions() { return filterOptions; } public void setFilterOptions(List<FilterOption> filterOptions) { this.filterOptions = filterOptions; } public void addFilterOption(String field, String value) { filterOptions.add(new FilterOption(field, value)); } public String getFilterConjunction() { return filterConjunction; } public void setFilterConjunction(String filterConjunction) { this.filterConjunction = filterConjunction; } public void apply(UploadedDatum item) { if (item.getDatumType() != filterType) { throw new IllegalArgumentException("Data types do not match; I filter " + filterType.getPlural() + " but received a " + item.getDatumType().getSingular()); } if (filterOptions.size() < 1 || (targetAttributeId == null && targetCapabilityId == null && targetComponentId == null)) { return; } boolean matchesAny = false; boolean matchesAll = true; for (FilterOption option : filterOptions) { String value = item.getField(option.getType()); if (value != null) { if (value.contains(option.getValue())) { matchesAny = true; } else { matchesAll = false; } } } if (matchesAll || ("any".equals(filterConjunction) && matchesAny)) { if (targetAttributeId != null) { item.setTargetAttributeId(targetAttributeId); } if (targetComponentId != null) { item.setTargetComponentId(targetComponentId); } if (targetCapabilityId != null) { item.setTargetCapabilityId(targetCapabilityId); } } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Attribute. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Attribute implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.ATTRIBUTE; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long attributeId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; /** * Ordering hint for views displaying Attributes. Lower values should be put higher in the list. * Note that value is NOT guaranteed to be unique or greater than zero. */ @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); public Attribute() {} public Attribute(long parentProjectId) { this.parentProjectId = parentProjectId; } /** * @return the Attribute instance's attribute ID. It will be null if it has not been saved yet. */ public Long getAttributeId() { return attributeId; } @Override public Long getId() { return getAttributeId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } /** * Sets the Attribute's ID. Note this should only be called as a direct result of persisting * the Attribute in the data store. */ public void setAttributeId(long attributeId) { this.attributeId = attributeId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public long getDisplayOrder() { return displayOrder; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public void addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(attributeId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); } public void addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(attributeId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Interface for surfacing inform from uploaded data to enable display. * * @author chrsmith@google.com (Chris Smith) */ public interface UploadedDatum { public DatumType getDatumType(); /** Returns the text for any links to this datum. */ public String getLinkText(); /** Returns an external URL to refer to the uploaded datum. */ public String getLinkUrl(); /** Returns a Tool Tip to display when hovering over the datum. */ public String getToolTip(); /** State, such as Open, Passed, Failed, etc. */ public String getState(); /** Date the item entered the state, eg: day it passed, date it was submitted. */ public Long getStateDate(); /** Methods for checking if the datum is attached to an Attribute, Component, or Capability. */ public boolean isAttachedToAttribute(); public boolean isAttachedToComponent(); public boolean isAttachedToCapability(); public void setTargetCapabilityId(Long targetCapabilityId); public Long getTargetCapabilityId(); public void setTargetAttributeId(Long targetAttributeId); public Long getTargetAttributeId(); public void setTargetComponentId(Long targetComponentId); public Long getTargetComponentId(); public Long getParentProjectId(); public void setParentProjectId(Long parentProjectId); public Long getExternalId(); public void setExternalId(Long externalId); public Long getInternalId(); public void setInternalId(Long internalId); /** Allows generic access for filtering. */ public String getField(String field); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; /** * Simple pair class. * * @author jimr@google.com (Jim Reardon) */ public class Pair<A, B> implements Serializable { public final A first; public final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Component. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Component implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.COMPONENT; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long componentId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; /** * Ordering hint for views displaying Attributes. Lower values should be put higher in the list. * Note that value is NOT guaranteed to be unique or greater than zero. */ @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); public Component() { } public Component(long parentProjectId) { this.parentProjectId = parentProjectId; } public Long getComponentId() { return componentId; } @Override public Long getId() { return getComponentId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } public void setComponentId(long componentId) { this.componentId = componentId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public long getDisplayOrder() { return displayOrder; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public void addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(componentId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); } public void addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(componentId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enumeration for storing potential failure rates. * * @author chrsmith@google.com (Chris Smith) */ public enum FailureRate { NA (-2, "n/a"), VERY_RARELY (0, "Rarely"), SELDOM (1, "Seldom"), OCCASIONALLY (2, "Occasionally"), OFTEN (3, "Often"); private final int ordinal; private final String description; private FailureRate(int ordinal, String description) { this.ordinal = ordinal; this.description = description; } public int getOrdinal() { return ordinal; } public String getDescription() { return description; } /** * Convert FailureRate.getDescription() into the original FailureRate instance. Enum.getValue * cannot be used because that requires the "ALL_CAPS" form of the value, rather than * the "User Friendly" getName version. */ public static FailureRate fromDescription(String name) { for (FailureRate rate : FailureRate.values()) { if (rate.getDescription().equals(name)) { return rate; } } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.testing; import com.google.gwt.user.client.rpc.AsyncCallback; import org.easymock.EasyMock; import org.easymock.IAnswer; /** * Utility class for simplifying Easy Mock unit tests. * * @author chrsmith@google.com (Chris Smith) */ public abstract class EasyMockUtils { private EasyMockUtils() {} /** Sets the return value for the last call to EasyMock. */ public static <T> void setLastReturnValue(final T result) { EasyMock.expectLastCall().andReturn(result); } /** * Gets the {@link AsyncCallback} (last parameter of the previous function call) and ensures that * the onSuccess method gets called with the given result. This is needed because GWT's async RPC * calls return their value as part of an {@link AsyncCallback}, which is difficult to mock. */ public static <T> void setLastAsyncCallbackSuccessWithResult(final T result) { EasyMock.expectLastCall().andAnswer(new IAnswer<T>() { @SuppressWarnings("unchecked") @Override public T answer() throws Throwable { final Object[] arguments = EasyMock.getCurrentArguments(); AsyncCallback<T> callback = (AsyncCallback<T>) arguments[arguments.length - 1]; callback.onSuccess(result); return null; } }); } /** * Gets the {@link AsyncCallback} (last parameter of the previous function call) and ensures that * the onFailure method gets called with the given {@code Throwable}. */ public static <T> void setLastAsyncCallbackFailure(final Throwable exception) { EasyMock.expectLastCall().andAnswer(new IAnswer<T>() { @SuppressWarnings("unchecked") @Override public T answer() throws Throwable { final Object[] arguments = EasyMock.getCurrentArguments(); AsyncCallback<T> callback = (AsyncCallback<T>) arguments[arguments.length - 1]; callback.onFailure(exception); return null; } }); } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.Context; import android.net.Uri; import android.preference.RingtonePreference; import android.util.AttributeSet; public class AlarmRingtonePreference extends RingtonePreference { private Uri ringtone; private Context context; private Str str; public AlarmRingtonePreference(Context c, AttributeSet attrs){ super(c, attrs); context = c; str = new Str(context.getResources()); } @Override protected Uri onRestoreRingtone() { return ringtone; } public void setValue(String s) { String summary = str.currently_set_to; if (s == null || s.equals("")) { ringtone = null; summary += str.silent; } else { ringtone = Uri.parse(s); android.media.Ringtone r = android.media.RingtoneManager.getRingtone(context, ringtone); if (r == null) { ringtone = null; summary += str.silent; } else { summary += r.getTitle(context); } } setSummary(summary); } }
Java
/* Copyright (c) 2009, 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences sp_store = context.getSharedPreferences("sp_store", 0); String startPref = settings.getString(SettingsActivity.KEY_AUTOSTART, "auto"); if (startPref.equals("always") || (startPref.equals("auto") && sp_store.getBoolean(BatteryIndicatorService.KEY_SERVICE_DESIRED, false))){ ComponentName comp = new ComponentName(context.getPackageName(), BatteryIndicatorService.class.getName()); context.startService(new Intent().setComponent(comp)); } } }
Java
/* Copyright (c) 2009, 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.os.Bundle; import android.os.Handler; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceScreen; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.WindowManager; import java.util.Locale; public class SettingsActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { public static final String KEY_COLOR_SETTINGS = "color_settings"; public static final String KEY_TIME_SETTINGS = "time_settings"; public static final String KEY_ALARM_SETTINGS = "alarm_settings"; public static final String KEY_ALARM_EDIT_SETTINGS = "alarm_edit_settings"; public static final String KEY_OTHER_SETTINGS = "other_settings"; public static final String KEY_CONFIRM_DISABLE_LOCKING = "confirm_disable_lock_screen"; public static final String KEY_FINISH_AFTER_TOGGLE_LOCK = "finish_after_toggle_lock"; public static final String KEY_FINISH_AFTER_BATTERY_USE = "finish_after_battery_use"; public static final String KEY_NOTIFY_WHEN_KG_DISABLED = "notify_when_kg_disabled"; public static final String KEY_AUTO_DISABLE_LOCKING = "auto_disable_lock_screen"; public static final String KEY_DISALLOW_DISABLE_LOCK_SCREEN = "disallow_disable_lock_screen"; public static final String KEY_MAIN_NOTIFICATION_PRIORITY = "main_notification_priority"; public static final String KEY_ENABLE_LOGGING = "enable_logging"; public static final String KEY_LOG_EVERYTHING = "log_everything"; public static final String KEY_MAX_LOG_AGE = "max_log_age"; public static final String KEY_MW_THEME = "main_window_theme"; public static final String KEY_ICON_PLUGIN = "icon_plugin"; public static final String KEY_CONVERT_F = "convert_to_fahrenheit"; public static final String KEY_AUTOSTART = "autostart"; public static final String KEY_CHARGE_AS_TEXT = "charge_as_text"; public static final String KEY_ONE_PERCENT_HACK = "one_percent_hack"; public static final String KEY_TEN_PERCENT_MODE = "ten_percent_mode"; public static final String KEY_STATUS_DUR_EST = "status_dur_est"; public static final String KEY_CAT_COLOR = "category_color"; public static final String KEY_CAT_PLUGIN_SETTINGS = "category_plugin_settings"; public static final String KEY_PLUGIN_SETTINGS = "plugin_settings"; public static final String KEY_RED = "use_red"; public static final String KEY_RED_THRESH = "red_threshold"; public static final String KEY_AMBER = "use_amber"; public static final String KEY_AMBER_THRESH = "amber_threshold"; public static final String KEY_GREEN = "use_green"; public static final String KEY_GREEN_THRESH = "green_threshold"; public static final String KEY_COLOR_PREVIEW = "color_preview"; public static final String KEY_USB_CHARGE_TIME = "usb_charge_time"; public static final String KEY_AC_CHARGE_TIME = "ac_charge_time"; public static final String KEY_LIGHT_USAGE_TIME = "light_usage_time"; public static final String KEY_NORMAL_USAGE_TIME = "normal_usage_time"; public static final String KEY_HEAVY_USAGE_TIME = "heavy_usage_time"; public static final String KEY_CONSTANT_USAGE_TIME = "constant_usage_time"; public static final String KEY_SHOW_NOTIFICATION_TIME = "show_notification_time"; public static final String KEY_SHOW_CHARGE_TIME = "show_charge_time"; public static final String KEY_SHOW_LIGHT_USAGE = "show_light_usage"; public static final String KEY_SHOW_NORMAL_USAGE = "show_normal_usage"; public static final String KEY_SHOW_HEAVY_USAGE = "show_heavy_usage"; public static final String KEY_SHOW_CONSTANT_USAGE = "show_constant_usage"; public static final String KEY_FIRST_RUN = "first_run"; //public static final String KEY_LANGUAGE_OVERRIDE = "language_override"; private static final String[] PARENTS = {KEY_SHOW_CHARGE_TIME, KEY_SHOW_CHARGE_TIME, /* Keep these doubled */ KEY_ENABLE_LOGGING, KEY_ENABLE_LOGGING, /* keys first! */ KEY_RED, KEY_AMBER, KEY_GREEN, KEY_SHOW_LIGHT_USAGE, KEY_SHOW_NORMAL_USAGE, KEY_SHOW_HEAVY_USAGE, KEY_SHOW_CONSTANT_USAGE}; private static final String[] DEPENDENTS = {KEY_USB_CHARGE_TIME, KEY_AC_CHARGE_TIME, KEY_LOG_EVERYTHING, KEY_MAX_LOG_AGE, KEY_RED_THRESH, KEY_AMBER_THRESH, KEY_GREEN_THRESH, KEY_LIGHT_USAGE_TIME, KEY_NORMAL_USAGE_TIME, KEY_HEAVY_USAGE_TIME, KEY_CONSTANT_USAGE_TIME}; private static final String[] LIST_PREFS = {KEY_AUTOSTART, KEY_MW_THEME, KEY_STATUS_DUR_EST, KEY_RED_THRESH, KEY_AMBER_THRESH, KEY_GREEN_THRESH, KEY_USB_CHARGE_TIME, KEY_AC_CHARGE_TIME, KEY_LIGHT_USAGE_TIME, KEY_NORMAL_USAGE_TIME, KEY_HEAVY_USAGE_TIME, KEY_CONSTANT_USAGE_TIME, KEY_MAIN_NOTIFICATION_PRIORITY, KEY_MAX_LOG_AGE, KEY_ICON_PLUGIN/*, KEY_LANGUAGE_OVERRIDE*/}; private static final String[] RESET_SERVICE = {KEY_CONVERT_F, KEY_CHARGE_AS_TEXT, KEY_STATUS_DUR_EST, KEY_AUTO_DISABLE_LOCKING, KEY_RED, KEY_RED_THRESH, KEY_AMBER, KEY_AMBER_THRESH, KEY_GREEN, KEY_GREEN_THRESH, KEY_NOTIFY_WHEN_KG_DISABLED, KEY_ICON_PLUGIN, KEY_ONE_PERCENT_HACK, /*KEY_LANGUAGE_OVERRIDE,*/ KEY_SHOW_NOTIFICATION_TIME, KEY_TEN_PERCENT_MODE}; /* 10% mode changes color settings */ private static final String[] RESET_SERVICE_WITH_CANCEL_NOTIFICATION = {KEY_MAIN_NOTIFICATION_PRIORITY}; public static final String EXTRA_SCREEN = "com.darshancomputing.BatteryIndicatorPro.PrefScreen"; public static final int RED = 0; public static final int AMBER = 1; public static final int GREEN = 2; /* Red must go down to 0 and green must go up to 100, which is why they aren't listed here. */ public static final int RED_ICON_MAX = 30; public static final int AMBER_ICON_MIN = 0; public static final int AMBER_ICON_MAX = 50; public static final int GREEN_ICON_MIN = 20; public static final int RED_SETTING_MIN = 5; public static final int RED_SETTING_MAX = 30; public static final int AMBER_SETTING_MIN = 10; public static final int AMBER_SETTING_MAX = 50; public static final int GREEN_SETTING_MIN = 20; /* public static final int GREEN_SETTING_MAX = 100; /* TODO: use this, and possibly set it to 95. */ public static final int CHARGE_COUNTER_LEGIT_MAX = 115; /* From what I understand, charge_counter can go somewhat over 100; I'm guessing at 115 being an appropriate cutoff point. */ private static final int DIALOG_CONFIRM_TEN_PERCENT_ENABLE = 0; private static final int DIALOG_CONFIRM_TEN_PERCENT_DISABLE = 1; private Intent biServiceIntent; private BIServiceConnection biServiceConnection; private Resources res; private PreferenceScreen mPreferenceScreen; private SharedPreferences mSharedPreferences; private String pref_screen; private ColorPreviewPreference cpbPref; private ListPreference redThresh; private ListPreference amberThresh; private ListPreference greenThresh; private Boolean redEnabled; private Boolean amberEnabled; private Boolean greenEnabled; private int iRedThresh; private int iAmberThresh; private int iGreenThresh; private Boolean ten_percent_mode; private ListPreference pluginPref; private String currentPlugin; private String iconPluginSummaryOverride; private int menu_res = R.menu.settings; private static final String[] fivePercents = { "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "100"}; /* Also includes 5 and 15, as the orginal Droid (and presumably similarly crippled devices) goes by 5% once you get below 20%. */ private static final String[] tenPercentEntries = { "5", "10", "15", "20", "30", "40", "50", "60", "70", "80", "90", "100"}; /* Setting Red and Amber values like this allows the Service to follow the same algorithm no matter what. */ private static final String[] tenPercentValues = { "6", "11", "16", "21", "31", "41", "51", "61", "71", "81", "91", "101"}; /* Returns a two-item array of the start and end indices into the above arrays. */ private int[] indices(int x, int y) { int[] a = new int[2]; int i; /* How many values to remove from the front */ int j; /* How many values to remove from the end */ if (ten_percent_mode) { for (i = 0; i < tenPercentEntries.length - 1; i++) if (Integer.valueOf(tenPercentEntries[i]) >= Integer.valueOf(x)) break; j = (100 - y) / 10; } else { i = (x / 5) - 1; j = (100 - y) / 5; } a[0] = i; a[1] = j; return a; } private static final Object[] EMPTY_OBJECT_ARRAY = {}; private static final Class[] EMPTY_CLASS_ARRAY = {}; private java.lang.reflect.Method backupMethod; private Object backupManager; private Boolean backupAvailable; //private String oldLanguage = null; private final Handler mHandler = new Handler(); Runnable rShowPluginSettings = new Runnable() { public void run() { if (biServiceConnection.biService == null) { bindService(biServiceIntent, biServiceConnection, 0); return; } Boolean hasSettings = false; try { hasSettings = biServiceConnection.biService.pluginHasSettings(); } catch (Exception e) { e.printStackTrace(); } if (! hasSettings) { PreferenceCategory cat = (PreferenceCategory) mPreferenceScreen.findPreference(KEY_CAT_PLUGIN_SETTINGS); cat.removeAll(); cat.setLayoutResource(R.layout.hidden); } else { Preference p = (Preference) mPreferenceScreen.findPreference(KEY_PLUGIN_SETTINGS); p.setEnabled(true); } mHandler.removeCallbacks(rShowPluginSettings); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); try { Class<?> c = Class.forName("android.app.backup.BackupManager"); backupMethod = c.getMethod("dataChanged", new Class[] {}); java.lang.reflect.Constructor<?> init = c.getConstructor(android.content.Context.class); backupManager = init.newInstance(this); backupAvailable = true; } catch (Exception e) { backupAvailable = false; } Intent intent = getIntent(); pref_screen = intent.getStringExtra(EXTRA_SCREEN); res = getResources(); if (res.getBoolean(R.bool.override_list_activity_layout)) { setContentView(R.layout.list_activity); getListView().setDivider(res.getDrawable(R.drawable.my_divider)); } // Stranglely disabled by default for API level 14+ ///*v11*/ if (res.getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); mSharedPreferences = getPreferenceManager().getSharedPreferences(); //oldLanguage = mSharedPreferences.getString(KEY_LANGUAGE_OVERRIDE, "default"); if (pref_screen == null) { setPrefScreen(R.xml.main_pref_screen); setWindowSubtitle(res.getString(R.string.settings_activity_subtitle)); } else if (pref_screen.equals(KEY_COLOR_SETTINGS)) { setPrefScreen(R.xml.color_pref_screen); setWindowSubtitle(res.getString(R.string.color_settings)); menu_res = R.menu.color_settings; ten_percent_mode = mSharedPreferences.getBoolean(KEY_TEN_PERCENT_MODE, false); cpbPref = (ColorPreviewPreference) mPreferenceScreen.findPreference(KEY_COLOR_PREVIEW); if (ten_percent_mode) cpbPref.setLayoutResource(R.layout.hidden); pluginPref = (ListPreference) mPreferenceScreen.findPreference(KEY_ICON_PLUGIN); setPluginPrefEntriesAndValues(pluginPref); currentPlugin = pluginPref.getValue(); redThresh = (ListPreference) mPreferenceScreen.findPreference(KEY_RED_THRESH); amberThresh = (ListPreference) mPreferenceScreen.findPreference(KEY_AMBER_THRESH); greenThresh = (ListPreference) mPreferenceScreen.findPreference(KEY_GREEN_THRESH); if (currentPlugin.equals("none")) { PreferenceCategory cat; cat = (PreferenceCategory) mPreferenceScreen.findPreference(KEY_CAT_PLUGIN_SETTINGS); cat.removeAll(); boolean v11 = false; ///*v11*/ v11 = true; if (v11) { cat.setLayoutResource(R.layout.hidden); cat = (PreferenceCategory) mPreferenceScreen.findPreference(KEY_CAT_COLOR); cat.removeAll(); cat.setLayoutResource(R.layout.none); } else { cat.setLayoutResource(R.layout.none); redEnabled = mSharedPreferences.getBoolean( KEY_RED, false); amberEnabled = mSharedPreferences.getBoolean(KEY_AMBER, false); greenEnabled = mSharedPreferences.getBoolean(KEY_GREEN, false); iRedThresh = Integer.valueOf( redThresh.getValue()); /* Entries don't exist yet */ iAmberThresh = Integer.valueOf(amberThresh.getValue()); iGreenThresh = Integer.valueOf(greenThresh.getValue()); mPreferenceScreen.findPreference(KEY_TEN_PERCENT_MODE) .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() { public boolean onPreferenceChange(final Preference preference, final Object newValue) { showDialog((Boolean) newValue ? DIALOG_CONFIRM_TEN_PERCENT_ENABLE : DIALOG_CONFIRM_TEN_PERCENT_DISABLE); return false; } }); if (ten_percent_mode) { /* These should always correspond to the logical (entry) value, not the actual stored value. */ iRedThresh--; iAmberThresh--; } validateColorPrefs(null); } } else { PreferenceCategory cat = (PreferenceCategory) mPreferenceScreen.findPreference(KEY_CAT_COLOR); cat.removeAll(); cat.setLayoutResource(R.layout.none); mHandler.postDelayed(rShowPluginSettings, 100); mHandler.postDelayed(rShowPluginSettings, 300); mHandler.postDelayed(rShowPluginSettings, 600); mHandler.postDelayed(rShowPluginSettings, 1000); } /* Hide any themes that might be disabled (e.g. Tablets show different themes) */ ListPreference lp = (ListPreference) mPreferenceScreen.findPreference(KEY_MW_THEME); CharSequence[] oldEntries = lp.getEntries(); CharSequence[] oldValues = lp.getEntryValues(); int nActiveThemes = 0; for (int i=0; i < oldEntries.length; i++) { if (! oldValues[i].equals("DISABLED")) nActiveThemes++; } CharSequence[] newEntries = new CharSequence[nActiveThemes]; CharSequence[] newValues = new CharSequence[nActiveThemes]; for (int i=0,j=0; i < oldEntries.length; i++) { if (oldValues[i].equals("DISABLED")) continue; newEntries[j] = oldEntries[i]; newValues[j] = oldValues[i]; j++; } lp.setEntries(newEntries); lp.setEntryValues(newValues); } else if (pref_screen.equals(KEY_TIME_SETTINGS)) { setPrefScreen(R.xml.time_pref_screen); setWindowSubtitle(res.getString(R.string.time_settings)); } else if (pref_screen.equals(KEY_OTHER_SETTINGS)) { setPrefScreen(R.xml.other_pref_screen); setWindowSubtitle(res.getString(R.string.other_settings)); enableOnePercentIfAppropriate(); /*ListPreference lp = (ListPreference) mPreferenceScreen.findPreference(KEY_LANGUAGE_OVERRIDE); CharSequence[] values = lp.getEntryValues(); CharSequence[] entries = new CharSequence[values.length]; for (int i=0; i < values.length; ++i) { if (values[i].toString().equals("default")) entries[i] = res.getString(R.string.lang_system_selected); else { Locale locale = codeToLocale(values[i].toString()); entries[i] = locale.getDisplayName(locale); } } lp.setEntries(entries);*/ } else { setPrefScreen(R.xml.main_pref_screen); } for (int i=0; i < PARENTS.length; i++) setEnablednessOfDeps(i); for (int i=0; i < LIST_PREFS.length; i++) updateListPrefSummary(LIST_PREFS[i]); updateConvertFSummary(); setEnablednessOfMutuallyExclusive(KEY_CONFIRM_DISABLE_LOCKING, KEY_FINISH_AFTER_TOGGLE_LOCK); biServiceIntent = new Intent(this, BatteryIndicatorService.class); biServiceConnection = new BIServiceConnection(); bindService(biServiceIntent, biServiceConnection, 0); } public static Locale codeToLocale (String code) { String[] parts = code.split("_"); if (parts.length > 1) return new Locale(parts[0], parts[1]); else return new Locale(parts[0]); } private void setWindowSubtitle(String subtitle) { if (res.getBoolean(R.bool.long_activity_names)) setTitle(res.getString(R.string.app_full_name) + " - " + subtitle); else setTitle(subtitle); } private void setPrefScreen(int resource) { addPreferencesFromResource(resource); mPreferenceScreen = getPreferenceScreen(); } private void restartThisScreen() { ComponentName comp = new ComponentName(getPackageName(), SettingsActivity.class.getName()); Intent intent = new Intent().setComponent(comp); intent.putExtra(EXTRA_SCREEN, pref_screen); startActivity(intent); finish(); } /*private void restartIfLanguageChanged() { String curLanguage = mSharedPreferences.getString(KEY_LANGUAGE_OVERRIDE, "default"); if (curLanguage.equals(oldLanguage)) return; Str.overrideLanguage(res, getWindowManager(), curLanguage); restartThisScreen(); }*/ private void resetService() { resetService(false); } private void resetService(boolean cancelFirst) { try { biServiceConnection.biService.reloadSettings(cancelFirst); } catch (Exception e) { startService(new Intent(this, BatteryIndicatorService.class)); } } @Override protected void onDestroy() { super.onDestroy(); if (biServiceConnection != null) unbindService(biServiceConnection); } @Override protected void onResume() { super.onResume(); //restartIfLanguageChanged(); mSharedPreferences.registerOnSharedPreferenceChangeListener(this); } @Override protected void onPause() { super.onPause(); mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(menu_res, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_help: ComponentName comp = new ComponentName(getPackageName(), SettingsHelpActivity.class.getName()); Intent intent = new Intent().setComponent(comp); if (pref_screen != null) intent.putExtra(EXTRA_SCREEN, pref_screen); startActivity(intent); return true; case R.id.menu_get_plugins: startActivity(new Intent(Intent.ACTION_VIEW, android.net.Uri.parse ("http://bi-icon-plugins.darshancomputing.com/"))); return true; case android.R.id.home: startActivity(new Intent(this, BatteryIndicator.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); Str str = new Str(getResources()); switch (id) { /* Android saves and reuses these dialogs; we want different titles for each, hence two IDs */ case DIALOG_CONFIRM_TEN_PERCENT_ENABLE: case DIALOG_CONFIRM_TEN_PERCENT_DISABLE: builder.setTitle(ten_percent_mode ? str.confirm_ten_percent_disable : str.confirm_ten_percent_enable) .setMessage(str.confirm_ten_percent_hint) .setCancelable(false) .setPositiveButton(str.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { ten_percent_mode = ! ten_percent_mode; ((CheckBoxPreference) mPreferenceScreen.findPreference(KEY_TEN_PERCENT_MODE)).setChecked(ten_percent_mode); di.cancel(); restartThisScreen(); } }) .setNegativeButton(str.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { di.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; } public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { String key = preference.getKey(); if (key == null) { return false; } else if (key.equals(KEY_COLOR_SETTINGS) || key.equals(KEY_TIME_SETTINGS) || key.equals(KEY_OTHER_SETTINGS)) { ComponentName comp = new ComponentName(getPackageName(), SettingsActivity.class.getName()); startActivity(new Intent().setComponent(comp).putExtra(EXTRA_SCREEN, key)); return true; } else if (key.equals(KEY_ALARM_SETTINGS)) { ComponentName comp = new ComponentName(getPackageName(), AlarmsActivity.class.getName()); startActivity(new Intent().setComponent(comp)); return true; } else if (key.equals(KEY_PLUGIN_SETTINGS)) { biServiceConnection.biService.configurePlugin(); return true; } else { return false; } } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { mSharedPreferences.unregisterOnSharedPreferenceChangeListener(this); if (backupAvailable) { try{ backupMethod.invoke(backupManager, EMPTY_OBJECT_ARRAY); } catch (Exception e) { } } if (key.equals(KEY_RED)) { redEnabled = mSharedPreferences.getBoolean(KEY_RED, false); } else if (key.equals(KEY_AMBER)) { amberEnabled = mSharedPreferences.getBoolean(KEY_AMBER, false); } else if (key.equals(KEY_GREEN)) { greenEnabled = mSharedPreferences.getBoolean(KEY_GREEN, false); } else if (key.equals(KEY_RED_THRESH)) { iRedThresh = Integer.valueOf((String) redThresh.getEntry()); } else if (key.equals(KEY_AMBER_THRESH)) { iAmberThresh = Integer.valueOf((String) amberThresh.getEntry()); } else if (key.equals(KEY_GREEN_THRESH)) { iGreenThresh = Integer.valueOf((String) greenThresh.getEntry()); } if (key.equals(KEY_RED) || key.equals(KEY_RED_THRESH) || key.equals(KEY_AMBER) || key.equals(KEY_AMBER_THRESH) || key.equals(KEY_GREEN) || key.equals(KEY_GREEN_THRESH)) { validateColorPrefs(key); } if (key.equals(KEY_TEN_PERCENT_MODE)) resetColorsToDefaults(); if (key.equals(KEY_ICON_PLUGIN)) { resetService(); // TODO: This didn't used to be here, and things seemed to work fine, but it seems like it should be needed... restartThisScreen(); } for (int i=0; i < PARENTS.length; i++) { if (key.equals(PARENTS[i])) { setEnablednessOfDeps(i); if (i == 0) setEnablednessOfDeps(1); /* Doubled charge key */ if (i == 2) setEnablednessOfDeps(3); /* Doubled charge key */ break; } } for (int i=0; i < LIST_PREFS.length; i++) { if (key.equals(LIST_PREFS[i])) { updateListPrefSummary(LIST_PREFS[i]); break; } } if (key.equals(KEY_CONFIRM_DISABLE_LOCKING) || key.equals(KEY_FINISH_AFTER_TOGGLE_LOCK)) setEnablednessOfMutuallyExclusive(KEY_CONFIRM_DISABLE_LOCKING, KEY_FINISH_AFTER_TOGGLE_LOCK); if (key.equals(KEY_CONVERT_F)) { updateConvertFSummary(); } /*if (key.equals(KEY_LANGUAGE_OVERRIDE)) { Str.overrideLanguage(res, getWindowManager(), mSharedPreferences.getString(SettingsActivity.KEY_LANGUAGE_OVERRIDE, "default")); restartThisScreen(); }*/ for (int i=0; i < RESET_SERVICE.length; i++) { if (key.equals(RESET_SERVICE[i])) { resetService(); break; } } for (int i=0; i < RESET_SERVICE_WITH_CANCEL_NOTIFICATION.length; i++) { if (key.equals(RESET_SERVICE_WITH_CANCEL_NOTIFICATION[i])) { resetService(true); break; } } mSharedPreferences.registerOnSharedPreferenceChangeListener(this); } private void updateConvertFSummary() { Preference pref = (CheckBoxPreference) mPreferenceScreen.findPreference(KEY_CONVERT_F); if (pref == null) return; pref.setSummary(res.getString(R.string.currently_using) + " " + (mSharedPreferences.getBoolean(KEY_CONVERT_F, false) ? res.getString(R.string.fahrenheit) : res.getString(R.string.celsius))); } private void setEnablednessOfDeps(int index) { Preference dependent = mPreferenceScreen.findPreference(DEPENDENTS[index]); if (dependent == null) return; if (mSharedPreferences.getBoolean(PARENTS[index], false)) dependent.setEnabled(true); else dependent.setEnabled(false); updateListPrefSummary(DEPENDENTS[index]); } private void setEnablednessOfMutuallyExclusive(String key1, String key2) { Preference pref1 = mPreferenceScreen.findPreference(key1); Preference pref2 = mPreferenceScreen.findPreference(key2); if (pref1 == null) return; if (mSharedPreferences.getBoolean(key1, false)) pref2.setEnabled(false); else if (mSharedPreferences.getBoolean(key2, false)) pref1.setEnabled(false); else { pref1.setEnabled(true); pref2.setEnabled(true); } } private void enableOnePercentIfAppropriate() { Preference pref = mPreferenceScreen.findPreference(KEY_ONE_PERCENT_HACK); try { java.io.FileReader fReader = new java.io.FileReader("/sys/class/power_supply/battery/charge_counter"); java.io.BufferedReader bReader = new java.io.BufferedReader(fReader); if (Integer.valueOf(bReader.readLine()) <= CHARGE_COUNTER_LEGIT_MAX) pref.setEnabled(true); } catch (Exception e) {} } private void updateListPrefSummary(String key) { ListPreference pref; try { /* Code is simplest elsewhere if we call this on all dependents, but some aren't ListPreferences. */ pref = (ListPreference) mPreferenceScreen.findPreference(key); } catch (java.lang.ClassCastException e) { return; } if (pref == null) return; if (pref.isEnabled()) { pref.setSummary(res.getString(R.string.currently_set_to) + pref.getEntry()); } else { pref.setSummary(res.getString(R.string.currently_disabled)); } if (key.equals(KEY_ICON_PLUGIN) && iconPluginSummaryOverride != null) pref.setSummary(iconPluginSummaryOverride); } private void validateColorPrefs(String changedKey) { if (redThresh == null) return; String lowest; if (changedKey == null) { setColorPrefEntriesAndValues(redThresh, RED_SETTING_MIN, RED_SETTING_MAX); /* Older version had a higher max; user's setting could be too high. */ if (iRedThresh > RED_SETTING_MAX) { redThresh.setValue("" + RED_SETTING_MAX); iRedThresh = RED_SETTING_MAX; if (ten_percent_mode) iRedThresh--; } } if (changedKey == null || changedKey.equals(KEY_RED) || changedKey.equals(KEY_RED_THRESH) || changedKey.equals(KEY_AMBER)) { if (amberEnabled) { lowest = setColorPrefEntriesAndValues(amberThresh, determineMin(AMBER), AMBER_SETTING_MAX); if (iAmberThresh < Integer.valueOf(lowest)) { amberThresh.setValue(lowest); iAmberThresh = Integer.valueOf(lowest); if (ten_percent_mode) iAmberThresh--; updateListPrefSummary(KEY_AMBER_THRESH); } } } if (changedKey == null || !changedKey.equals(KEY_GREEN_THRESH)) { if (greenEnabled) { lowest = setColorPrefEntriesAndValues(greenThresh, determineMin(GREEN), 100); if (iGreenThresh < Integer.valueOf(lowest)) { greenThresh.setValue(lowest); iGreenThresh = Integer.valueOf(lowest); updateListPrefSummary(KEY_GREEN_THRESH); } } } updateColorPreviewBar(); } /* Does the obvious and returns the lowest value. */ private String setColorPrefEntriesAndValues(ListPreference lpref, int min, int max) { String[] entries, values; int i, j; int[] a; a = indices(min, max); i = a[0]; j = a[1]; if (ten_percent_mode) { entries = new String[tenPercentEntries.length - i - j]; values = new String[tenPercentEntries.length - i - j]; System.arraycopy(tenPercentEntries, i, entries, 0, entries.length); System.arraycopy(tenPercentValues , i, values, 0, values.length); if (lpref.equals(greenThresh)) values = entries; } else { entries = values = new String[fivePercents.length - i - j]; System.arraycopy(fivePercents, i, entries, 0, entries.length); } lpref.setEntries(entries); lpref.setEntryValues(values); return values[0]; } private void setPluginPrefEntriesAndValues(ListPreference lpref) { String prefix = "BI Plugin - "; PackageManager pm = getPackageManager(); java.util.List<PackageInfo> packages = pm.getInstalledPackages(0); java.util.List<String> entriesList = new java.util.ArrayList<String>(); java.util.List<String> valuesList = new java.util.ArrayList<String>(); entriesList.add(res.getString(R.string.none)); valuesList.add("none"); int nPackages = packages.size(); for (int i=0; i < nPackages; i++) { PackageInfo pi = packages.get(i); if (pi.packageName.matches("com\\.darshancomputing\\.BatteryIndicatorPro\\.IconPluginV1\\..+")){ String entry = (String) pm.getApplicationLabel(pi.applicationInfo); if (entry.startsWith(prefix)) entry = entry.substring(prefix.length()); entriesList.add(entry); valuesList.add(pi.packageName); } } if (entriesList.size() > 1) iconPluginSummaryOverride = null; else iconPluginSummaryOverride = res.getString(R.string.no_plugins_installed_summary); lpref.setEntries ((String[]) entriesList.toArray(new String[entriesList.size()])); lpref.setEntryValues((String[]) valuesList.toArray(new String[entriesList.size()])); // If the previously selected plugin was uninstalled, revert to "None" //if (! valuesList.contains(lpref.getValue())) lpref.setValueIndex(0); if (lpref.getEntry() == null) lpref.setValueIndex(0); } private void resetColorsToDefaults() { SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putBoolean(KEY_RED, res.getBoolean(R.bool.default_use_red)); editor.putBoolean(KEY_AMBER, res.getBoolean(R.bool.default_use_amber)); editor.putBoolean(KEY_GREEN, res.getBoolean(R.bool.default_use_green)); if (mSharedPreferences.getBoolean(KEY_TEN_PERCENT_MODE, false)){ editor.putString( KEY_RED_THRESH, res.getString(R.string.default_red_thresh10 )); editor.putString(KEY_AMBER_THRESH, res.getString(R.string.default_amber_thresh10)); editor.putString(KEY_GREEN_THRESH, res.getString(R.string.default_green_thresh10)); } else { editor.putString( KEY_RED_THRESH, res.getString(R.string.default_red_thresh )); editor.putString(KEY_AMBER_THRESH, res.getString(R.string.default_amber_thresh)); editor.putString(KEY_GREEN_THRESH, res.getString(R.string.default_green_thresh)); } editor.commit(); } /* Determine the minimum valid threshold setting for a particular color, based on other active settings, with red being independent, amber depending on red, and green depending on both others. */ private int determineMin(int color) { switch (color) { case RED: return RED_SETTING_MIN; case AMBER: if (redEnabled) /* In 10% mode, we might want +10, but xToY10() will sort it out if +5 is too small. */ return java.lang.Math.max(iRedThresh + 5, AMBER_SETTING_MIN); else return AMBER_SETTING_MIN; case GREEN: int i; if (amberEnabled) i = iAmberThresh; else if (redEnabled) i = iRedThresh; else return GREEN_SETTING_MIN; if (ten_percent_mode) /* We'll usually want +10, but it could be just +5. xToY10() will sort it out if +5 is too small. */ return java.lang.Math.max(i + 5, GREEN_SETTING_MIN); else return java.lang.Math.max(i, GREEN_SETTING_MIN); default: return GREEN_SETTING_MIN; } } private void updateColorPreviewBar() { if (cpbPref == null) return; cpbPref.redThresh = redEnabled ? iRedThresh : 0; cpbPref.amberThresh = amberEnabled ? iAmberThresh : 0; cpbPref.greenThresh = greenEnabled ? iGreenThresh : 100; } }
Java
/* Copyright (c) 2009, 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.text.util.Linkify; import android.view.MenuItem; import android.widget.TextView; public class HelpActivity extends Activity { private static final int[] HAS_LINKS = {R.id.introduction, R.id.changelog, R.id.limitations, R.id.acknowledgments, R.id.translations, R.id.contact}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Stranglely disabled by default for API level 14+ ///*v11*/ if (getResources().getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); setContentView(R.layout.help); TextView tv; MovementMethod linkMovement = LinkMovementMethod.getInstance(); for (int i=0; i < HAS_LINKS.length; i++) { tv = (TextView) findViewById(HAS_LINKS[i]); tv.setMovementMethod(linkMovement); tv.setAutoLinkMask(Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); } tv = (TextView) findViewById(R.id.version); try { tv.setText(getResources().getString(R.string.app_full_name) + " " + getPackageManager().getPackageInfo(getPackageName(), 0).versionName); } catch (Exception e) { tv.setText("..."); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: startActivity(new Intent(this, BatteryIndicator.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.text.util.Linkify; import android.view.MenuItem; import android.widget.TextView; public class SettingsHelpActivity extends Activity { private Resources res; private int[] has_links = {}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String pref_screen = intent.getStringExtra(SettingsActivity.EXTRA_SCREEN); res = getResources(); // Stranglely disabled by default for API level 14+ ///*v11*/ if (res.getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); if (pref_screen == null) { setContentView(R.layout.main_settings_help); setWindowSubtitle(res.getString(R.string.settings_activity_subtitle)); } else if (pref_screen.equals(SettingsActivity.KEY_COLOR_SETTINGS)) { setContentView(R.layout.color_settings_help); setWindowSubtitle(res.getString(R.string.color_settings)); } else if (pref_screen.equals(SettingsActivity.KEY_TIME_SETTINGS)) { setContentView(R.layout.time_settings_help); setWindowSubtitle(res.getString(R.string.time_settings)); } else if (pref_screen.equals(SettingsActivity.KEY_OTHER_SETTINGS)) { setContentView(R.layout.other_settings_help); setWindowSubtitle(res.getString(R.string.other_settings)); has_links = new int[] {R.id.one_percent_hack}; } else if (pref_screen.equals(SettingsActivity.KEY_ALARM_SETTINGS)) { setContentView(R.layout.alarm_settings_help); setWindowSubtitle(res.getString(R.string.alarm_settings)); } else if (pref_screen.equals(SettingsActivity.KEY_ALARM_EDIT_SETTINGS)) { setContentView(R.layout.alarm_edit_help); setWindowSubtitle(res.getString(R.string.alarm_settings_subtitle)); } else { setContentView(R.layout.main_settings_help); } TextView tv; MovementMethod linkMovement = LinkMovementMethod.getInstance(); for (int i=0; i < has_links.length; i++) { tv = (TextView) findViewById(has_links[i]); tv.setMovementMethod(linkMovement); tv.setAutoLinkMask(Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES); } } private void setWindowSubtitle(String subtitle) { if (res.getBoolean(R.bool.long_activity_names)) setTitle(res.getString(R.string.app_full_name) + " - " + subtitle); else setTitle(subtitle); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: startActivity(new Intent(this, BatteryIndicator.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onResume() { super.onResume(); } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.AlertDialog; import android.app.Dialog; import android.app.ListActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.res.Resources; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.preference.PreferenceManager; import android.text.method.LinkMovementMethod; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.text.DateFormat; import java.util.Date; public class LogViewActivity extends ListActivity { private LogDatabase logs; private Resources res; private Context context; private SharedPreferences settings; private Str str; private Col col; private Cursor mCursor; private LayoutInflater mInflater; private LogAdapter mAdapter; private TextView header_text; private Boolean reversed = false; private Boolean convertF; private static final int DIALOG_CONFIRM_CLEAR_LOGS = 0; private static final String[] CSV_ORDER = {LogDatabase.KEY_TIME, LogDatabase.KEY_STATUS_CODE, LogDatabase.KEY_CHARGE, LogDatabase.KEY_TEMPERATURE, LogDatabase.KEY_VOLTAGE}; private static final IntentFilter batteryChangedFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); private final Handler mHandler = new Handler(); private final Runnable mUpdateStatus = new Runnable() { public void run() { reloadList(false); } }; private final BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (! Intent.ACTION_BATTERY_CHANGED.equals(action)) return; /* Give the service a couple seconds to process the update */ mHandler.postDelayed(mUpdateStatus, 2 * 1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); res = getResources(); // Stranglely disabled by default for API level 14+ ///*v11*/ if (res.getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); setWindowSubtitle(res.getString(R.string.log_view_activity_subtitle)); settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); convertF = settings.getBoolean(SettingsActivity.KEY_CONVERT_F, false); str = new Str(res); col = new Col(); if (res.getBoolean(R.bool.override_list_activity_layout)) { setContentView(R.layout.list_activity); getListView().setDivider(res.getDrawable(R.drawable.my_divider)); } View logs_header = View.inflate(context, R.layout.logs_header, null); getListView().addHeaderView(logs_header, null, false); header_text = (TextView) logs_header.findViewById(R.id.header_text); logs = new LogDatabase(context); mCursor = logs.getAllLogs(false); startManagingCursor(mCursor); mInflater = LayoutInflater.from(this); mAdapter = new LogAdapter(context, mCursor); setListAdapter(mAdapter); setHeaderText(); } private void setWindowSubtitle(String subtitle) { if (res.getBoolean(R.bool.long_activity_names)) setTitle(res.getString(R.string.app_full_name) + " - " + subtitle); else setTitle(subtitle); } @Override protected void onDestroy() { super.onDestroy(); mCursor.close(); logs.close(); } @Override protected void onResume() { super.onResume(); registerReceiver(mBatteryInfoReceiver, batteryChangedFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(mBatteryInfoReceiver); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); switch (id) { case DIALOG_CONFIRM_CLEAR_LOGS: builder.setTitle(str.confirm_clear_logs) .setPositiveButton(str.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { logs.clearAllLogs(); reloadList(false); di.cancel(); } }) .setNegativeButton(str.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { di.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.logs, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); switch (mCursor.getCount()) { case 0: menu.findItem(R.id.menu_clear).setEnabled(false); menu.findItem(R.id.menu_export).setEnabled(false); menu.findItem(R.id.menu_reverse).setEnabled(false); break; case 1: menu.findItem(R.id.menu_clear).setEnabled(true); menu.findItem(R.id.menu_export).setEnabled(true); menu.findItem(R.id.menu_reverse).setEnabled(false); break; default: menu.findItem(R.id.menu_clear).setEnabled(true); menu.findItem(R.id.menu_export).setEnabled(true); menu.findItem(R.id.menu_reverse).setEnabled(true); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear: showDialog(DIALOG_CONFIRM_CLEAR_LOGS); return true; case R.id.menu_export: exportCSV(); return true; case R.id.menu_reverse: reversed = (reversed) ? false : true; reloadList(true); return true; case android.R.id.home: startActivity(new Intent(this, BatteryIndicator.class)); return true; default: return super.onOptionsItemSelected(item); } } private void reloadList(Boolean newQuery){ if (newQuery) { stopManagingCursor(mCursor); mCursor = logs.getAllLogs(reversed); startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); } else { mCursor.requery(); } setHeaderText(); } private void setHeaderText() { int count = mCursor.getCount(); if (count == 0) header_text.setText(str.logs_empty); else header_text.setText(str.n_log_items(count)); } private void exportCSV() { String state = Environment.getExternalStorageState(); if (state != null && state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) { Toast.makeText(context, str.read_only_storage, Toast.LENGTH_SHORT).show(); return; } else if (state == null || !state.equals(Environment.MEDIA_MOUNTED)) { Toast.makeText(context, str.inaccessible_w_reason + state, Toast.LENGTH_SHORT).show(); return; } Date d = new Date(); String csvFileName = "BatteryIndicatorPro-Logs-" + d.getTime() + ".csv"; File root = Environment.getExternalStorageDirectory(); File csvFile = new File(root, csvFileName); String[] csvFields = {str.date, str.time, str.status, str.charge, str.temperature, str.voltage}; try { if (!csvFile.createNewFile() || !csvFile.canWrite()) { Toast.makeText(context, str.inaccessible_storage, Toast.LENGTH_SHORT).show(); return; } BufferedWriter buf = new BufferedWriter(new FileWriter(csvFile)); int cols = csvFields.length; int i; for (i = 0; i < cols; i++) { buf.write(csvFields[i]); if (i != cols - 1) buf.write(","); } buf.write("\r\n"); int statusCode; int[] statusCodes; int status, plugged, status_age; String s; for (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) { cols = CSV_ORDER.length; for (i = 0; i < cols; i++) { if (CSV_ORDER[i].equals(LogDatabase.KEY_TIME)) { d.setTime(mCursor.getLong(mAdapter.timeIndex)); buf.write(mAdapter.dateFormat.format(d) + "," + mAdapter.timeFormat.format(d) + ","); } else if (CSV_ORDER[i].equals(LogDatabase.KEY_STATUS_CODE)) { statusCode = mCursor.getInt(mAdapter.statusCodeIndex); statusCodes = LogDatabase.decodeStatus(statusCode); status = statusCodes[0]; plugged = statusCodes[1]; status_age = statusCodes[2]; if (status_age == LogDatabase.STATUS_OLD) s = str.log_statuses_old[status]; else s = str.log_statuses[status]; if (plugged > 0) s += " " + str.pluggeds[plugged]; buf.write(s + ","); } else if (CSV_ORDER[i].equals(LogDatabase.KEY_CHARGE)) { buf.write(String.valueOf(mCursor.getInt(mAdapter.chargeIndex)) + ","); } else if (CSV_ORDER[i].equals(LogDatabase.KEY_TEMPERATURE)) { buf.write(String.valueOf(mCursor.getInt(mAdapter.temperatureIndex) / 10.0) + ","); } else if (CSV_ORDER[i].equals(LogDatabase.KEY_VOLTAGE)) { buf.write(String.valueOf(mCursor.getInt(mAdapter.voltageIndex) / 1000.0)); } } buf.write("\r\n"); } buf.close(); } catch (Exception e) { Toast.makeText(context, str.inaccessible_storage, Toast.LENGTH_SHORT).show(); return; } Toast.makeText(context, str.file_written, Toast.LENGTH_SHORT).show(); } private class LogAdapter extends CursorAdapter { public int statusCodeIndex, chargeIndex, timeIndex, temperatureIndex, voltageIndex; public DateFormat dateFormat, timeFormat; private Date d = new Date(); public LogAdapter(Context context, Cursor cursor) { super(context, cursor); dateFormat = android.text.format.DateFormat.getDateFormat(context); timeFormat = android.text.format.DateFormat.getTimeFormat(context); statusCodeIndex = cursor.getColumnIndexOrThrow(LogDatabase.KEY_STATUS_CODE); chargeIndex = cursor.getColumnIndexOrThrow(LogDatabase.KEY_CHARGE); timeIndex = cursor.getColumnIndexOrThrow(LogDatabase.KEY_TIME); temperatureIndex = cursor.getColumnIndexOrThrow(LogDatabase.KEY_TEMPERATURE); voltageIndex = cursor.getColumnIndexOrThrow(LogDatabase.KEY_VOLTAGE); } public View newView(Context context, Cursor cursor, ViewGroup parent) { return mInflater.inflate(R.layout.log_item , parent, false); } public void bindView(View view, Context context, Cursor cursor) { TextView status_tv = (TextView) view.findViewById(R.id.status); TextView percent_tv = (TextView) view.findViewById(R.id.percent); TextView time_tv = (TextView) view.findViewById(R.id.time); TextView temp_volt_tv = (TextView) view.findViewById(R.id.temp_volt); int statusCode = cursor.getInt(statusCodeIndex); int[] statusCodes = LogDatabase.decodeStatus(statusCode); int status = statusCodes[0]; int plugged = statusCodes[1]; int status_age = statusCodes[2]; String s; if (status_age == LogDatabase.STATUS_OLD) { status_tv.setTextColor(col.old_status); percent_tv.setTextColor(col.old_status); s = str.log_statuses_old[status]; } else { switch (status) { case 5: status_tv.setTextColor(col.charged); percent_tv.setTextColor(col.charged); break; case 0: status_tv.setTextColor(col.unplugged); percent_tv.setTextColor(col.unplugged); break; case 2: default: status_tv.setTextColor(col.plugged); percent_tv.setTextColor(col.plugged); } s = str.log_statuses[status]; } if (plugged > 0) s += " " + str.pluggeds[plugged]; status_tv.setText(s); percent_tv.setText("" + cursor.getInt(chargeIndex) + "%"); d.setTime(cursor.getLong(timeIndex)); time_tv.setText(dateFormat.format(d) + " " + timeFormat.format(d)); int temperature = cursor.getInt(temperatureIndex); if (temperature != 0) temp_volt_tv.setText("" + str.formatTemp(temperature, convertF)); else temp_volt_tv.setText(""); /* TextViews are reused */ int voltage = cursor.getInt(voltageIndex); if (voltage != 0) temp_volt_tv.setText(((String) temp_volt_tv.getText()) + " / " + str.formatVoltage(voltage)); } } private class Col { public int old_status; public int charged; public int plugged; public int unplugged; public Col() { old_status = res.getColor(R.color.old_status); charged = res.getColor(R.color.charged); plugged = res.getColor(R.color.plugged); unplugged = res.getColor(R.color.unplugged); } } }
Java
/* Copyright (c) 2009, 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.content.res.Resources; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.widget.Button; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class BatteryIndicator extends Activity { private Intent biServiceIntent; private SharedPreferences settings; private SharedPreferences sp_store; private final BIServiceConnection biServiceConnection = new BIServiceConnection(); private static final Intent batteryUseIntent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); private static final IntentFilter batteryChangedFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); private Resources res; private Context context; private String themeName; private Boolean disallowLockButton; MainWindowTheme.Theme theme; private int percent = -1; private Button battery_use_b; private Button toggle_lock_screen_b; private boolean early_exit = false; private String oldLanguage = null; private static final int DIALOG_CONFIRM_DISABLE_KEYGUARD = 0; private static final int DIALOG_CONFIRM_CLOSE = 1; private static final int DIALOG_FIRST_RUN = 2; private static final int DIALOG_NEED_UNINSTALL = 3; private final Handler mHandler = new Handler(); private final Runnable mUpdateStatus = new Runnable() { public void run() { updateStatus(); updateLockscreenButton(); updateTimes(); } }; private final BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (! Intent.ACTION_BATTERY_CHANGED.equals(action)) return; int level = intent.getIntExtra("level", -1); int scale = intent.getIntExtra("scale", 100); percent = level * 100 / scale; mHandler.post(mUpdateStatus); /* Give the service a second to process the update */ mHandler.postDelayed(mUpdateStatus, 1 * 1000); /* Just in case 1 second wasn't enough */ mHandler.postDelayed(mUpdateStatus, 4 * 1000); } }; @Override protected void onCreate(Bundle savedInstanceState) { res = getResources(); context = getApplicationContext(); settings = PreferenceManager.getDefaultSharedPreferences(context); super.onCreate(savedInstanceState); setContentView(R.layout.main); try { (new AlarmDatabase(context)).close(); } catch (Exception e) { early_exit = true; showDialog(DIALOG_NEED_UNINSTALL); } if (!early_exit) { sp_store = context.getSharedPreferences("sp_store", 0); if (settings.contains(BatteryIndicatorService.KEY_LAST_PERCENT)) { switch_to_sp_store(); } disallowLockButton = settings.getBoolean(SettingsActivity.KEY_DISALLOW_DISABLE_LOCK_SCREEN, false); themeName = settings.getString(SettingsActivity.KEY_MW_THEME, "default"); setTheme(); if (settings.getBoolean(SettingsActivity.KEY_FIRST_RUN, true)) { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(SettingsActivity.KEY_FIRST_RUN, false); editor.commit(); /* May have upgraded from older version before key_first_run; only show if it really is first run */ if (sp_store.getInt(BatteryIndicatorService.KEY_LAST_PERCENT, -1) == -1) showDialog(DIALOG_FIRST_RUN); } biServiceIntent = new Intent(this, BatteryIndicatorService.class); startService(biServiceIntent); bindService(biServiceIntent, biServiceConnection, 0); SharedPreferences.Editor editor = sp_store.edit(); editor.putBoolean(BatteryIndicatorService.KEY_SERVICE_DESIRED, true); editor.commit(); if (! res.getBoolean(R.bool.show_main_title)) setTitle(""); } } @Override protected void onDestroy() { super.onDestroy(); if (!early_exit) unbindService(biServiceConnection); } /*private void restartIfLanguageChanged() { String curLanguage = settings.getString(SettingsActivity.KEY_LANGUAGE_OVERRIDE, "default"); if (curLanguage.equals(oldLanguage)) return; Str.overrideLanguage(res, getWindowManager(), curLanguage); mStartActivity(BatteryIndicator.class); finish(); }*/ @Override protected void onResume() { super.onResume(); if (!early_exit) { registerReceiver(mBatteryInfoReceiver, batteryChangedFilter); } } @Override protected void onPause() { super.onPause(); if (!early_exit) unregisterReceiver(mBatteryInfoReceiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_logs: mStartActivity(LogViewActivity.class); return true; case R.id.menu_settings: mStartActivity(SettingsActivity.class); return true; case R.id.menu_close: showDialog(DIALOG_CONFIRM_CLOSE); return true; case R.id.menu_help: mStartActivity(HelpActivity.class); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String oldThemeName = themeName; Boolean oldDisallow = disallowLockButton; themeName = settings.getString(SettingsActivity.KEY_MW_THEME, "default"); disallowLockButton = settings.getBoolean(SettingsActivity.KEY_DISALLOW_DISABLE_LOCK_SCREEN, false); if (! oldThemeName.equals(themeName) || oldDisallow != disallowLockButton) { setTheme(); } } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; AlertDialog.Builder builder = new AlertDialog.Builder(this); switch (id) { case DIALOG_CONFIRM_DISABLE_KEYGUARD: builder.setTitle(res.getString(R.string.confirm_disable)) .setMessage(res.getString(R.string.confirm_disable_hint)) .setCancelable(false) .setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { setDisableLocking(true); di.cancel(); } }) .setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { di.cancel(); } }); dialog = builder.create(); break; case DIALOG_CONFIRM_CLOSE: builder.setTitle(res.getString(R.string.confirm_close)) .setMessage(res.getString(R.string.confirm_close_hint)) .setPositiveButton(res.getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { SharedPreferences.Editor editor = sp_store.edit(); editor.putBoolean(BatteryIndicatorService.KEY_SERVICE_DESIRED, false); editor.commit(); finishActivity(1); stopService(biServiceIntent); finish(); di.cancel(); } }) .setNegativeButton(res.getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { di.cancel(); } }); dialog = builder.create(); break; case DIALOG_FIRST_RUN: LayoutInflater inflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.first_run_message, (LinearLayout) findViewById(R.id.layout_root)); builder.setTitle(res.getString(R.string.first_run_title)) .setView(layout) .setPositiveButton(res.getString(R.string.okay), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { di.cancel(); } }); dialog = builder.create(); break; case DIALOG_NEED_UNINSTALL: builder.setTitle(res.getString(R.string.need_uninstall)) .setMessage(res.getString(R.string.need_uninstall_hint)) .setPositiveButton(res.getString(R.string.okay), new DialogInterface.OnClickListener() { public void onClick(DialogInterface di, int id) { try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.darshancomputing.BatteryIndicatorPro"))); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Sorry, can't launch Market!", Toast.LENGTH_SHORT).show(); } startActivity(new Intent(Intent.ACTION_DELETE, Uri.parse("package:com.darshancomputing.BatteryIndicatorPro"))); finish(); di.cancel(); } }); dialog = builder.create(); break; default: dialog = null; } return dialog; } private void updateStatus() { int last_percent = sp_store.getInt(BatteryIndicatorService.KEY_LAST_PERCENT, -1); int last_status = sp_store.getInt(BatteryIndicatorService.KEY_LAST_STATUS, 0); TextView status_since = (TextView) findViewById(R.id.status_since_t); String s; if (last_status == 0) s = res.getString(R.string.discharging_from) + " " + last_percent + res.getString(R.string.percent_symbol); else if (last_status == 2) s = res.getString(R.string.charging_from) + " " + last_percent + res.getString(R.string.percent_symbol); else s = res.getString(R.string.fully_charged); status_since.setText(s); } private void updateLockscreenButton() { if (sp_store.getBoolean(BatteryIndicatorService.KEY_DISABLE_LOCKING, false)) toggle_lock_screen_b.setText(res.getString(R.string.reenable_lock_screen)); else toggle_lock_screen_b.setText(res.getString(R.string.disable_lock_screen)); } private void setDisableLocking(boolean b) { SharedPreferences.Editor editor = sp_store.edit(); editor.putBoolean(BatteryIndicatorService.KEY_DISABLE_LOCKING, b); editor.commit(); biServiceConnection.biService.reloadSettings(); updateLockscreenButton(); if (settings.getBoolean(SettingsActivity.KEY_FINISH_AFTER_TOGGLE_LOCK, false)) finish(); } /* Battery Use */ private final OnClickListener buButtonListener = new OnClickListener() { public void onClick(View v) { try { startActivity(batteryUseIntent); if (settings.getBoolean(SettingsActivity.KEY_FINISH_AFTER_BATTERY_USE, false)) finish(); } catch (Exception e) { Toast.makeText(context, res.getString(R.string.one_six_needed), Toast.LENGTH_SHORT).show(); battery_use_b.setEnabled(false); } } }; /* Toggle Lock Screen */ private final OnClickListener tlsButtonListener = new OnClickListener() { public void onClick(View v) { if (sp_store.getBoolean(BatteryIndicatorService.KEY_DISABLE_LOCKING, false)) { setDisableLocking(false); } else { if (settings.getBoolean(SettingsActivity.KEY_CONFIRM_DISABLE_LOCKING, true)) { showDialog(DIALOG_CONFIRM_DISABLE_KEYGUARD); } else { setDisableLocking(true); } } } }; private void mStartActivity(Class c) { ComponentName comp = new ComponentName(getPackageName(), c.getName()); //startActivity(new Intent().setComponent(comp)); startActivityForResult(new Intent().setComponent(comp), 1); //finish(); } private void bindButtons() { if (getPackageManager().resolveActivity(batteryUseIntent, 0) == null) { battery_use_b.setEnabled(false); /* TODO: change how the disabled button looks */ } else { battery_use_b.setOnClickListener(buButtonListener); } toggle_lock_screen_b.setOnClickListener(tlsButtonListener); } private void switch_to_sp_store() { SharedPreferences.Editor settings_ed = settings.edit(); SharedPreferences.Editor sp_store_ed = sp_store.edit(); sp_store_ed.putString(BatteryIndicatorService.KEY_LAST_STATUS_SINCE, settings.getString(BatteryIndicatorService.KEY_LAST_STATUS_SINCE, "")); settings_ed.remove(BatteryIndicatorService.KEY_LAST_STATUS_SINCE); sp_store_ed.putLong(BatteryIndicatorService.KEY_LAST_STATUS_CTM, settings.getLong(BatteryIndicatorService.KEY_LAST_STATUS_CTM, -1)); settings_ed.remove(BatteryIndicatorService.KEY_LAST_STATUS_CTM); sp_store_ed.putInt(BatteryIndicatorService.KEY_LAST_STATUS, settings.getInt(BatteryIndicatorService.KEY_LAST_STATUS, -1)); settings_ed.remove(BatteryIndicatorService.KEY_LAST_STATUS); sp_store_ed.putInt(BatteryIndicatorService.KEY_LAST_PERCENT, settings.getInt(BatteryIndicatorService.KEY_LAST_PERCENT, -1)); settings_ed.remove(BatteryIndicatorService.KEY_LAST_PERCENT); sp_store_ed.putInt(BatteryIndicatorService.KEY_LAST_PLUGGED, settings.getInt(BatteryIndicatorService.KEY_LAST_PLUGGED, -1)); settings_ed.remove(BatteryIndicatorService.KEY_LAST_PLUGGED); sp_store_ed.putInt(BatteryIndicatorService.KEY_PREVIOUS_CHARGE, settings.getInt(BatteryIndicatorService.KEY_PREVIOUS_CHARGE, -1)); settings_ed.remove(BatteryIndicatorService.KEY_PREVIOUS_CHARGE); sp_store_ed.putInt(BatteryIndicatorService.KEY_PREVIOUS_TEMP, settings.getInt(BatteryIndicatorService.KEY_PREVIOUS_TEMP, -1)); settings_ed.remove(BatteryIndicatorService.KEY_PREVIOUS_TEMP); sp_store_ed.putInt(BatteryIndicatorService.KEY_PREVIOUS_HEALTH, settings.getInt(BatteryIndicatorService.KEY_PREVIOUS_HEALTH, -1)); settings_ed.remove(BatteryIndicatorService.KEY_PREVIOUS_HEALTH); sp_store_ed.putBoolean(BatteryIndicatorService.KEY_SERVICE_DESIRED, settings.getBoolean(BatteryIndicatorService.KEY_SERVICE_DESIRED, false)); settings_ed.remove(BatteryIndicatorService.KEY_SERVICE_DESIRED); settings_ed.commit(); sp_store_ed.commit(); try { Class<?> c = Class.forName("android.app.backup.BackupManager"); java.lang.reflect.Method m = c.getMethod("dataChanged", new Class[] {}); java.lang.reflect.Constructor<?> init = c.getConstructor(android.content.Context.class); m.invoke(init.newInstance(this), new Object[] {}); } catch (Exception e) {} } private void setTheme() { theme = (new MainWindowTheme(themeName, context)).theme; LinearLayout main_layout = (LinearLayout) findViewById(R.id.main_layout); main_layout.removeAllViews(); LinearLayout main_frame = (LinearLayout) View.inflate(context, theme.mainFrameLayout, main_layout); main_layout.setPadding(theme.mainLayoutPaddingLeft, theme.mainLayoutPaddingTop, theme.mainLayoutPaddingRight, theme.mainLayoutPaddingBottom); updateTimes(); battery_use_b = (Button) main_frame.findViewById(R.id.battery_use_b); toggle_lock_screen_b = (Button) main_frame.findViewById(R.id.toggle_lock_screen_b); if (disallowLockButton) toggle_lock_screen_b.setEnabled(false); bindButtons(); } private void updateTimes() { for (int i = 0; i < theme.timeRemainingIds.length; i++) { LinearLayout ll = (LinearLayout) findViewById(theme.timeRemainingIds[i]); if (ll != null) { TextView label = (TextView) ll.findViewById(R.id.label); TextView time = (TextView) ll.findViewById(R.id.time); if (theme.timeRemainingVisible(i)) { label.setText(res.getString(theme.timeRemainingStrings[i])); label.setTextColor(res.getColor(theme.timeRemainingColors[i])); time.setText(theme.timeRemaining(i, percent)); time.setTextColor(res.getColor(theme.timeRemainingColors[i])); label.setVisibility(View.VISIBLE); time.setVisibility(View.VISIBLE); } else { label.setVisibility(View.GONE); time.setVisibility(View.GONE); } } } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.res.Resources; import android.view.WindowManager; /* TODO?: have a public instance in the service and grab the server's instance from all other classes? */ public class Str { private Resources res; public String degree_symbol; public String fahrenheit_symbol; public String celsius_symbol; public String volt_symbol; public String percent_symbol; public String since; public String default_status_dur_est; public String default_red_thresh; public String default_amber_thresh; public String default_green_thresh; public String default_max_log_age; public String default_main_notification_priority; public String logs_empty; public String confirm_clear_logs; public String confirm_ten_percent_enable; public String confirm_ten_percent_disable; public String confirm_ten_percent_hint; public String yes; public String cancel; public String currently_set_to; public String alarm_pref_not_used; public String silent; public String alarm_fully_charged; public String alarm_charge_drops; public String alarm_charge_rises; public String alarm_temp_rises; public String alarm_health_failure; public String alarm_text; public String inaccessible_storage; public String inaccessible_w_reason; public String read_only_storage; public String file_written; public String time; public String date; public String status; public String charge; public String temperature; public String voltage; public String[] statuses; public String[] log_statuses; public String[] log_statuses_old; public String[] healths; public String[] pluggeds; public String[] alarm_types_display; public String[] alarm_type_entries; public String[] alarm_type_values; public String[] temp_alarm_entries; public String[] temp_alarm_values; public Str(Resources r) { res = r; degree_symbol = res.getString(R.string.degree_symbol); fahrenheit_symbol = res.getString(R.string.fahrenheit_symbol); celsius_symbol = res.getString(R.string.celsius_symbol); volt_symbol = res.getString(R.string.volt_symbol); percent_symbol = res.getString(R.string.percent_symbol); since = res.getString(R.string.since); default_status_dur_est = res.getString(R.string.default_status_dur_est); default_red_thresh = res.getString(R.string.default_red_thresh); default_amber_thresh = res.getString(R.string.default_amber_thresh); default_green_thresh = res.getString(R.string.default_green_thresh); default_max_log_age = res.getString(R.string.default_max_log_age); default_main_notification_priority = res.getString(R.string.default_main_notification_priority); logs_empty = res.getString(R.string.logs_empty); confirm_clear_logs = res.getString(R.string.confirm_clear_logs); yes = res.getString(R.string.yes); cancel = res.getString(R.string.cancel); confirm_ten_percent_enable = res.getString(R.string.confirm_ten_percent_enable); confirm_ten_percent_disable = res.getString(R.string.confirm_ten_percent_disable); confirm_ten_percent_hint = res.getString(R.string.confirm_ten_percent_hint); currently_set_to = res.getString(R.string.currently_set_to); alarm_pref_not_used = res.getString(R.string.alarm_pref_not_used); silent = res.getString(R.string.silent); alarm_fully_charged = res.getString(R.string.alarm_fully_charged); alarm_charge_drops = res.getString(R.string.alarm_charge_drops); alarm_charge_rises = res.getString(R.string.alarm_charge_rises); alarm_temp_rises = res.getString(R.string.alarm_temp_rises); alarm_health_failure = res.getString(R.string.alarm_health_failure); alarm_text = res.getString(R.string.alarm_text); inaccessible_storage = res.getString(R.string.inaccessible_storage); inaccessible_w_reason = res.getString(R.string.inaccessible_w_reason); read_only_storage = res.getString(R.string.read_only_storage); file_written = res.getString(R.string.file_written); date = res.getString(R.string.date); time = res.getString(R.string.time); status = res.getString(R.string.status); charge = res.getString(R.string.charge); temperature = res.getString(R.string.temperature); voltage = res.getString(R.string.voltage); statuses = res.getStringArray(R.array.statuses); log_statuses = res.getStringArray(R.array.log_statuses); log_statuses_old = res.getStringArray(R.array.log_statuses_old); healths = res.getStringArray(R.array.healths); pluggeds = res.getStringArray(R.array.pluggeds); alarm_types_display = res.getStringArray(R.array.alarm_types_display); alarm_type_entries = res.getStringArray(R.array.alarm_type_entries); alarm_type_values = res.getStringArray(R.array.alarm_type_values); temp_alarm_entries = res.getStringArray(R.array.temp_alarm_entries); temp_alarm_values = res.getStringArray(R.array.temp_alarm_values); } public String for_n_hours(int n) { return String.format(res.getQuantityString(R.plurals.for_n_hours, n), n); } public String n_log_items(int n) { return String.format(res.getQuantityString(R.plurals.n_log_items, n), n); } /* temperature is the integer number of tenths of degrees Celcius, as returned by BatteryManager */ public String formatTemp(int temperature, boolean convertF, boolean includeTenths) { double d; String s; if (convertF){ d = java.lang.Math.round(temperature * 9 / 5.0) / 10.0 + 32.0; s = degree_symbol + fahrenheit_symbol; } else { d = temperature / 10.0; s = degree_symbol + celsius_symbol; } // Weird: the ternary operator seems to compile down to a "function" that has to return a single particular type //return "" + (includeTenths ? d : java.lang.Math.round(d)) + s; return (includeTenths ? String.valueOf(d) : String.valueOf(java.lang.Math.round(d))) + s; } public String formatTemp(int temperature, boolean convertF) { return formatTemp(temperature, convertF, true); } public String formatVoltage(int voltage) { return String.valueOf(voltage / 1000.0) + volt_symbol; } public static int indexOf(String[] a, String key) { for (int i=0, size=a.length; i < size; i++) if (key.equals(a[i])) return i; return -1; } public static void overrideLanguage(Resources res, WindowManager wm, String lang_override) { android.content.res.Configuration conf = res.getConfiguration(); if (! lang_override.equals("default")) { conf.locale = SettingsActivity.codeToLocale(lang_override); android.util.DisplayMetrics metrics = new android.util.DisplayMetrics(); wm.getDefaultDisplay().getMetrics(metrics); res.updateConfiguration(conf, metrics); } else { /* TODO: Somehow set to system default */ /* Perhaps showing a confirmation dialog, saying the app needs to close in order for change to take effect. You'd actually do that from SettingsActivity, so execution would never actually get here. */ } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.Context; import android.content.res.Resources; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.view.ViewGroup.LayoutParams; public class MainWindowTheme { private float density; private Resources res; public Theme theme; private SharedPreferences settings; private SharedPreferences sp_store; public MainWindowTheme(String themeName, Context context) { res = context.getResources(); DisplayMetrics metrics = new DisplayMetrics(); ((android.view.WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(metrics); density = metrics.density; if (themeName.equals("colorful")) { theme = new ColorfulTheme(); } else if (themeName.equals("full-dark")) { theme = new FullDarkTheme(); } else { theme = new DefaultTheme(); } settings = PreferenceManager.getDefaultSharedPreferences(context); sp_store = context.getSharedPreferences("sp_store", 0); } public abstract class Theme { public int mainFrameLayout; public int mainLayoutPaddingLeft; public int mainLayoutPaddingTop; public int mainLayoutPaddingRight; public int mainLayoutPaddingBottom; public int[] timeRemainingIds = {R.id.time_til_charged, R.id.light_usage, R.id.normal_usage, R.id.heavy_usage, R.id.constant_usage}; public int[] timeRemainingStrings = {R.string.fully_charged_in, R.string.light_usage, R.string.normal_usage, R.string.heavy_usage, R.string.constant_usage}; public int[] timeRemainingColors = {R.color.time_til_charged, R.color.light_usage, R.color.normal_usage, R.color.heavy_usage, R.color.constant_usage}; public String[] timeRemainingKeys = {"", SettingsActivity.KEY_LIGHT_USAGE_TIME, SettingsActivity.KEY_NORMAL_USAGE_TIME, SettingsActivity.KEY_HEAVY_USAGE_TIME, SettingsActivity.KEY_CONSTANT_USAGE_TIME}; public int[] timeRemainingDefaults = {0, R.string.default_light_usage_time, R.string.default_normal_usage_time, R.string.default_heavy_usage_time, R.string.default_constant_usage_time}; public String timeRemaining(int index, int percent) { String s; int t; if (percent == -1) return "..."; if (index == 0) { int last_plugged = sp_store.getInt("last_plugged", 2); if (last_plugged == 1) { s = settings.getString(SettingsActivity.KEY_AC_CHARGE_TIME, res.getString(R.string.default_ac_charge_time)); } else { s = settings.getString(SettingsActivity.KEY_USB_CHARGE_TIME, res.getString(R.string.default_usb_charge_time)); } t = 100 - percent; } else { s = settings.getString(timeRemainingKeys[index], res.getString(timeRemainingDefaults[index])); t = percent; } //return formatTimeRemaining(Math.round(t * Integer.valueOf(s) / (float) 100.0)); return formatTimeRemaining((t * Integer.valueOf(s) + 50) / 100); } /* Takes time as a whole number of minutes */ protected String formatTimeRemaining(int t) { return "" + (t / 60) + ":" + String.format("%02d", t % 60) + "h"; /* TODO: Make the h optional? translatable! */ } public boolean timeRemainingVisible(int index) { int last_status = sp_store.getInt("last_status", 0); /* TODO this should be a constant in Service */ switch (index) { case 0: if (last_status == 2 && settings.getBoolean(SettingsActivity.KEY_SHOW_CHARGE_TIME, /* TODO: Service constant */ res.getBoolean(R.bool.default_show_charge_time))) return true; break; case 1: if (settings.getBoolean(SettingsActivity.KEY_SHOW_LIGHT_USAGE, res.getBoolean(R.bool.default_show_light_usage))) return true; break; case 2: if (settings.getBoolean(SettingsActivity.KEY_SHOW_NORMAL_USAGE, res.getBoolean(R.bool.default_show_normal_usage))) return true; break; case 3: if (settings.getBoolean(SettingsActivity.KEY_SHOW_HEAVY_USAGE, res.getBoolean(R.bool.default_show_heavy_usage))) return true; break; case 4: if (settings.getBoolean(SettingsActivity.KEY_SHOW_CONSTANT_USAGE, res.getBoolean(R.bool.default_show_constant_usage))) return true; break; default: return true; } return false; } } private class DefaultTheme extends Theme { public DefaultTheme() { mainFrameLayout = R.layout.main_frame_default; int[] mainLayoutPadding = res.getIntArray(R.array.theme_default_main_layout_padding); mainLayoutPaddingLeft = (int) (mainLayoutPadding[0] * density); mainLayoutPaddingTop = (int) (mainLayoutPadding[1] * density); mainLayoutPaddingRight = (int) (mainLayoutPadding[2] * density); mainLayoutPaddingBottom = (int) (mainLayoutPadding[3] * density); } } private class ColorfulTheme extends DefaultTheme { public ColorfulTheme() { mainFrameLayout = R.layout.main_frame_colorful; } } private class FullDarkTheme extends Theme { public FullDarkTheme() { mainFrameLayout = R.layout.main_frame_full_dark; mainLayoutPaddingLeft = 0; mainLayoutPaddingTop = 0; mainLayoutPaddingRight = 0; mainLayoutPaddingBottom = 0; } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; import android.app.Service; public class PluginServiceConnection implements ServiceConnection { public Object service; public void onServiceConnected(ComponentName name, IBinder iBinder) { try { Class<?> c = iBinder.getClass(); java.lang.reflect.Method m = c.getMethod("getService", (Class[]) null); service = m.invoke(iBinder, (Object[]) null); } catch (Exception e) { e.printStackTrace(); service = null; } } public void onServiceDisconnected(ComponentName name) { service = null; } }
Java
/* Copyright (c) 2009, 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.KeyguardManager; import android.app.KeyguardManager.KeyguardLock; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.res.Resources; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.os.Binder; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.preference.PreferenceManager; import android.util.Log; import java.util.Date; public class BatteryIndicatorService extends Service { private final IntentFilter batteryChanged = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); private final IntentFilter userPresent = new IntentFilter(Intent.ACTION_USER_PRESENT); private PendingIntent mainWindowPendingIntent; private Intent alarmsIntent; private final PluginServiceConnection pluginServiceConnection = new PluginServiceConnection(); private Intent pluginIntent; private String pluginPackage; private NotificationManager mNotificationManager; private SharedPreferences settings; private SharedPreferences sp_store; private KeyguardLock kl; private KeyguardManager km; private android.os.Vibrator mVibrator; private android.media.AudioManager mAudioManager; private Boolean keyguardDisabled = false; private Notification kgUnlockedNotification; private Resources res; private Str str; private AlarmDatabase alarms; private static final String LOG_TAG = "BatteryIndicatorService"; private static final int NOTIFICATION_PRIMARY = 1; private static final int NOTIFICATION_KG_UNLOCKED = 2; private static final int NOTIFICATION_ALARM_CHARGE = 3; private static final int NOTIFICATION_ALARM_HEALTH = 4; private static final int NOTIFICATION_ALARM_TEMP = 5; private static final int STATUS_UNPLUGGED = 0; private static final int STATUS_UNKNOWN = 1; private static final int STATUS_CHARGING = 2; private static final int STATUS_DISCHARGING = 3; private static final int STATUS_NOT_CHARGING = 4; private static final int STATUS_FULLY_CHARGED = 5; private static final int STATUS_MAX = STATUS_FULLY_CHARGED; private static final int PLUGGED_UNPLUGGED = 0; private static final int PLUGGED_AC = 1; private static final int PLUGGED_USB = 2; private static final int PLUGGED_UNKNOWN = 3; private static final int PLUGGED_MAX = PLUGGED_UNKNOWN; private static final int HEALTH_UNKNOWN = 1; private static final int HEALTH_GOOD = 2; private static final int HEALTH_OVERHEAT = 3; private static final int HEALTH_DEAD = 4; private static final int HEALTH_OVERVOLTAGE = 5; private static final int HEALTH_FAILURE = 6; private static final int HEALTH_MAX = HEALTH_FAILURE; public static final String KEY_LAST_STATUS_SINCE = "last_status_since"; public static final String KEY_LAST_STATUS_CTM = "last_status_cTM"; public static final String KEY_LAST_STATUS = "last_status"; public static final String KEY_LAST_PERCENT = "last_percent"; public static final String KEY_LAST_PLUGGED = "last_plugged"; public static final String KEY_PREVIOUS_CHARGE = "previous_charge"; public static final String KEY_PREVIOUS_TEMP = "previous_temp"; public static final String KEY_PREVIOUS_HEALTH = "previous_health"; public static final String KEY_DISABLE_LOCKING = "disable_lock_screen"; public static final String KEY_SERVICE_DESIRED = "serviceDesired"; private static final Object[] EMPTY_OBJECT_ARRAY = {}; private static final Class[] EMPTY_CLASS_ARRAY = {}; private static final int defaultIcon0 = R.drawable.b000; private int chargingIcon0; /* Global variables for these Notification Runnables */ private Notification mainNotification; private int percent; private int status; private String mainNotificationTitle, mainNotificationText; private final Handler mHandler = new Handler(); private final Runnable mPluginNotify = new Runnable() { public void run() { try { mNotificationManager.cancel(NOTIFICATION_PRIMARY); if (pluginServiceConnection.service == null) return; Class<?> c = pluginServiceConnection.service.getClass(); java.lang.reflect.Method m = c.getMethod("notify", new Class[] {int.class, int.class, String.class, String.class, PendingIntent.class}); m.invoke(pluginServiceConnection.service, new Object[] {percent, status, mainNotificationTitle, mainNotificationText, mainWindowPendingIntent}); mHandler.removeCallbacks(mPluginNotify); mHandler.removeCallbacks(mNotify); } catch (Exception e) { e.printStackTrace(); } } }; private final Runnable mNotify = new Runnable() { public void run() { if (! pluginPackage.equals("none")) disconnectPlugin(); mNotificationManager.notify(NOTIFICATION_PRIMARY, mainNotification); mHandler.removeCallbacks(mPluginNotify); mHandler.removeCallbacks(mNotify); } }; @Override public void onCreate() { res = getResources(); str = new Str(res); Context context = getApplicationContext(); alarms = new AlarmDatabase(context); try { java.lang.reflect.Field f = R.drawable.class.getField("charging000"); chargingIcon0 = f.getInt(R.drawable.class); } catch (Exception e) { chargingIcon0 = defaultIcon0; } mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mVibrator = (android.os.Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); mAudioManager = (android.media.AudioManager) getSystemService(Context.AUDIO_SERVICE); settings = PreferenceManager.getDefaultSharedPreferences(context); sp_store = context.getSharedPreferences("sp_store", 0); Intent mainWindowIntent = new Intent(context, BatteryIndicator.class); mainWindowPendingIntent = PendingIntent.getActivity(context, 0, mainWindowIntent, 0); alarmsIntent = new Intent(context, AlarmsActivity.class); kgUnlockedNotification = new Notification(R.drawable.kg_unlocked, null, 0); kgUnlockedNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; kgUnlockedNotification.setLatestEventInfo(context, "Lock Screen Disabled", "Press to re-enable", mainWindowPendingIntent); km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); kl = km.newKeyguardLock(getPackageName()); if (sp_store.getBoolean(KEY_DISABLE_LOCKING, false)) setEnablednessOfKeyguard(false); pluginPackage = "none"; registerReceiver(mBatteryInfoReceiver, batteryChanged); } @Override public void onDestroy() { setEnablednessOfKeyguard(true); alarms.close(); if (! pluginPackage.equals("none")) disconnectPlugin(); unregisterReceiver(mBatteryInfoReceiver); mNotificationManager.cancelAll(); } @Override public IBinder onBind(Intent intent) { return mBinder; } public class LocalBinder extends Binder { public BatteryIndicatorService getService() { return BatteryIndicatorService.this; } } private final IBinder mBinder = new LocalBinder(); private final BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { mHandler.removeCallbacks(mPluginNotify); mHandler.removeCallbacks(mNotify); String desiredPluginPackage = settings.getString(SettingsActivity.KEY_ICON_PLUGIN, "none"); if (! pluginPackage.equals(desiredPluginPackage) && ! pluginPackage.equals("none")) disconnectPlugin(); if (! pluginPackage.equals(desiredPluginPackage) && ! desiredPluginPackage.equals("none")) { try { Context pluginContext = getApplicationContext().createPackageContext(desiredPluginPackage, Context.CONTEXT_INCLUDE_CODE); ClassLoader pluginClassLoader = pluginContext.getClassLoader(); Class pluginClass = pluginClassLoader.loadClass(desiredPluginPackage + ".PluginService"); pluginIntent = new Intent(pluginContext, pluginClass); startService(pluginIntent); if (! bindService(pluginIntent, pluginServiceConnection, 0)) { stopService(pluginIntent); throw new Exception(); } pluginPackage = desiredPluginPackage; } catch (Exception e) { e.printStackTrace(); pluginPackage = "none"; } } SharedPreferences.Editor editor = sp_store.edit(); String action = intent.getAction(); if (! Intent.ACTION_BATTERY_CHANGED.equals(action)) return; int level = intent.getIntExtra("level", 50); int scale = intent.getIntExtra("scale", 100); status = intent.getIntExtra("status", STATUS_UNKNOWN); int health = intent.getIntExtra("health", HEALTH_UNKNOWN); int plugged = intent.getIntExtra("plugged", PLUGGED_UNKNOWN); int temperature = intent.getIntExtra("temperature", 0); int voltage = intent.getIntExtra("voltage", 0); //String technology = intent.getStringExtra("technology"); percent = level * 100 / scale; if (settings.getBoolean(SettingsActivity.KEY_ONE_PERCENT_HACK, false)) { try { java.io.FileReader fReader = new java.io.FileReader("/sys/class/power_supply/battery/charge_counter"); java.io.BufferedReader bReader = new java.io.BufferedReader(fReader); int charge_counter = Integer.valueOf(bReader.readLine()); if (charge_counter > SettingsActivity.CHARGE_COUNTER_LEGIT_MAX) { disableOnePercentHack("charge_counter is too big to be actual charge"); } else { if (charge_counter > 100) charge_counter = 100; percent = charge_counter; } } catch (java.io.FileNotFoundException e) { /* These error messages are only really useful to me and might as well be left hardwired here in English. */ disableOnePercentHack("charge_counter file doesn't exist"); } catch (java.io.IOException e) { disableOnePercentHack("Error reading charge_counter file"); } } /* Just treating any unplugged status as simply "Unplugged" now. Note that the main activity now assumes that the status is always 0, 2, or 5 TODO */ if (plugged == PLUGGED_UNPLUGGED) status = STATUS_UNPLUGGED; if (status > STATUS_MAX) { status = STATUS_UNKNOWN; } if (health > HEALTH_MAX) { health = HEALTH_UNKNOWN; } if (plugged > PLUGGED_MAX){ plugged = PLUGGED_UNKNOWN; } /* I take advantage of (count on) R.java having resources alphabetical and incrementing by one */ int icon; ///*v11*//* // Hackish, ugly way to hide this in v11 version; Musn't use multi-line comments within this section if (settings.getBoolean(SettingsActivity.KEY_RED, res.getBoolean(R.bool.default_use_red)) && percent < Integer.valueOf(settings.getString(SettingsActivity.KEY_RED_THRESH, str.default_red_thresh)) && percent <= SettingsActivity.RED_ICON_MAX) { icon = R.drawable.r000 + percent - 0; } else if (settings.getBoolean(SettingsActivity.KEY_AMBER, res.getBoolean(R.bool.default_use_amber)) && percent < Integer.valueOf(settings.getString(SettingsActivity.KEY_AMBER_THRESH, str.default_amber_thresh)) && percent <= SettingsActivity.AMBER_ICON_MAX && percent >= SettingsActivity.AMBER_ICON_MIN){ icon = R.drawable.a000 + percent - 0; } else if (settings.getBoolean(SettingsActivity.KEY_GREEN, res.getBoolean(R.bool.default_use_green)) && percent >= Integer.valueOf(settings.getString(SettingsActivity.KEY_GREEN_THRESH, str.default_green_thresh)) && percent >= SettingsActivity.GREEN_ICON_MIN) { icon = R.drawable.g020 + percent - 20; } else { icon = R.drawable.b000 + percent; } ///*v11*/ // End v11 hidden section ///*v11*/ icon = ((status == STATUS_CHARGING) ? chargingIcon0 : defaultIcon0) + percent; String statusStr = str.statuses[status]; if (status == STATUS_CHARGING) statusStr += " " + str.pluggeds[plugged]; /* Add '(AC)' or '(USB)' */ int last_status = sp_store.getInt(KEY_LAST_STATUS, -1); /* There's a bug, at least on 1.5, or maybe depending on the hardware (I've noticed it on the MyTouch with 1.5) where USB is recognized as AC at first, then quickly changed to USB. So we need to test if plugged changed. */ int last_plugged = sp_store.getInt(KEY_LAST_PLUGGED, -1); long last_status_cTM = sp_store.getLong(KEY_LAST_STATUS_CTM, -1); int last_percent = sp_store.getInt(KEY_LAST_PERCENT, -1); int previous_charge = sp_store.getInt(KEY_PREVIOUS_CHARGE, 100); long currentTM = System.currentTimeMillis(); long statusDuration; String last_status_since = sp_store.getString(KEY_LAST_STATUS_SINCE, null); LogDatabase logs = new LogDatabase(context); if (last_status != status || last_status_cTM == -1 || last_percent == -1 || last_status_cTM > currentTM || last_status_since == null || last_plugged != plugged || (plugged == PLUGGED_UNPLUGGED && percent > previous_charge + 20)) { last_status_since = formatTime(new Date()); statusDuration = 0; if (settings.getBoolean(SettingsActivity.KEY_ENABLE_LOGGING, false)) { logs.logStatus(status, plugged, percent, temperature, voltage, currentTM, LogDatabase.STATUS_NEW); if (status != last_status && last_status == STATUS_UNPLUGGED) logs.prune(Integer.valueOf(settings.getString(SettingsActivity.KEY_MAX_LOG_AGE, str.default_max_log_age))); } editor.putString(KEY_LAST_STATUS_SINCE, last_status_since); editor.putLong(KEY_LAST_STATUS_CTM, currentTM); editor.putInt(KEY_LAST_STATUS, status); editor.putInt(KEY_LAST_PERCENT, percent); editor.putInt(KEY_LAST_PLUGGED, plugged); editor.putInt(KEY_PREVIOUS_CHARGE, percent); editor.putInt(KEY_PREVIOUS_TEMP, temperature); editor.putInt(KEY_PREVIOUS_HEALTH, health); last_status_cTM = currentTM; /* TODO: Af first glance, I think I want to do this, but think about it a bit and decide for sure... */ mNotificationManager.cancel(NOTIFICATION_ALARM_CHARGE); if (last_status != status && settings.getBoolean(SettingsActivity.KEY_AUTO_DISABLE_LOCKING, false)) { if (last_status == STATUS_UNPLUGGED) { editor.putBoolean(KEY_DISABLE_LOCKING, true); setEnablednessOfKeyguard(false); } else if (status == STATUS_UNPLUGGED) { editor.putBoolean(KEY_DISABLE_LOCKING, false); setEnablednessOfKeyguard(true); /* If the screen was on, "inside" the keyguard, when the keyguard was disabled, then we're still inside it now, even if the screen is off. So we aquire a wakelock that forces the screen to turn on, then release it. If the screen is on now, this has no effect, but if it's off, then either the user will press the power button or the screen will turn itself off after the normal timeout. Either way, when the screen goes off, the keyguard will now be enabled properly. */ PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, getPackageName()); wl.acquire(); wl.release(); } } } else { statusDuration = currentTM - last_status_cTM; if (settings.getBoolean(SettingsActivity.KEY_ENABLE_LOGGING, false) && settings.getBoolean(SettingsActivity.KEY_LOG_EVERYTHING, false)) logs.logStatus(status, plugged, percent, temperature, voltage, currentTM, LogDatabase.STATUS_OLD); if (percent % 10 == 0) { editor.putInt(KEY_PREVIOUS_CHARGE, percent); editor.putInt(KEY_PREVIOUS_TEMP, temperature); editor.putInt(KEY_PREVIOUS_HEALTH, health); } } logs.close(); /* Add half an hour, then divide. Should end up rounding to the closest hour. */ int statusDurationHours = (int)((statusDuration + (1000 * 60 * 30)) / (1000 * 60 * 60)); mainNotificationTitle = ""; if (settings.getBoolean(SettingsActivity.KEY_CHARGE_AS_TEXT, false)) mainNotificationTitle += percent + str.percent_symbol + " "; int status_dur_est = Integer.valueOf(settings.getString(SettingsActivity.KEY_STATUS_DUR_EST, str.default_status_dur_est)); if (statusDurationHours < status_dur_est) { mainNotificationTitle += statusStr + " " + str.since + " " + last_status_since; } else { mainNotificationTitle += statusStr + " " + str.for_n_hours(statusDurationHours); } Boolean convertF = settings.getBoolean(SettingsActivity.KEY_CONVERT_F, false); mainNotificationText = str.healths[health] + " / " + str.formatTemp(temperature, convertF); if (voltage > 500) mainNotificationText += " / " + str.formatVoltage(voltage); long when = 0; if (settings.getBoolean(SettingsActivity.KEY_SHOW_NOTIFICATION_TIME, false)) when = System.currentTimeMillis(); mainNotification = new Notification(icon, null, when); ///*v11*/ if (android.os.Build.VERSION.SDK_INT >= 16) { ///*v11*/ mainNotification.priority = Integer.valueOf(settings.getString(SettingsActivity.KEY_MAIN_NOTIFICATION_PRIORITY, str.default_main_notification_priority)); ///*v11*/ } mainNotification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR; mainNotification.setLatestEventInfo(context, mainNotificationTitle, mainNotificationText, mainWindowPendingIntent); if (! pluginPackage.equals("none")) { mHandler.postDelayed(mPluginNotify, 100); mHandler.postDelayed(mPluginNotify, 300); mHandler.postDelayed(mPluginNotify, 900); mHandler.postDelayed(mNotify, 1000); } else { mHandler.post(mNotify); } if (alarms.anyActiveAlarms()) { Cursor c; Notification notification; PendingIntent contentIntent = PendingIntent.getActivity(context, 0, alarmsIntent, 0); if (status == STATUS_FULLY_CHARGED && last_status == STATUS_CHARGING) { c = alarms.activeAlarmFull(); if (c != null) { notification = parseAlarmCursor(c); notification.setLatestEventInfo(context, str.alarm_fully_charged, str.alarm_text, contentIntent); mNotificationManager.notify(NOTIFICATION_ALARM_CHARGE, notification); c.close(); } } c = alarms.activeAlarmChargeDrops(percent, previous_charge); if (c != null) { editor.putInt(KEY_PREVIOUS_CHARGE, percent); notification = parseAlarmCursor(c); notification.setLatestEventInfo(context, str.alarm_charge_drops + c.getInt(alarms.INDEX_THRESHOLD) + str.percent_symbol, str.alarm_text, contentIntent); mNotificationManager.notify(NOTIFICATION_ALARM_CHARGE, notification); c.close(); } c = alarms.activeAlarmChargeRises(percent, previous_charge); if (c != null) { editor.putInt(KEY_PREVIOUS_CHARGE, percent); notification = parseAlarmCursor(c); notification.setLatestEventInfo(context, str.alarm_charge_rises + c.getInt(alarms.INDEX_THRESHOLD) + str.percent_symbol, str.alarm_text, contentIntent); mNotificationManager.notify(NOTIFICATION_ALARM_CHARGE, notification); c.close(); } c = alarms.activeAlarmTempRises(temperature, sp_store.getInt(KEY_PREVIOUS_TEMP, 1)); if (c != null) { editor.putInt(KEY_PREVIOUS_TEMP, temperature); notification = parseAlarmCursor(c); notification.setLatestEventInfo(context, str.alarm_temp_rises + str.formatTemp(c.getInt(alarms.INDEX_THRESHOLD), convertF, false), str.alarm_text, contentIntent); mNotificationManager.notify(NOTIFICATION_ALARM_TEMP, notification); c.close(); } if (health > HEALTH_GOOD && health != sp_store.getInt(KEY_PREVIOUS_HEALTH, HEALTH_GOOD)) { c = alarms.activeAlarmFailure(); if (c != null) { editor.putInt(KEY_PREVIOUS_HEALTH, health); notification = parseAlarmCursor(c); notification.setLatestEventInfo(context, str.alarm_health_failure + str.healths[health], str.alarm_text, contentIntent); mNotificationManager.notify(NOTIFICATION_ALARM_HEALTH, notification); c.close(); } } } editor.commit(); } }; private void disableOnePercentHack(String reason) { SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(SettingsActivity.KEY_ONE_PERCENT_HACK, false); editor.commit(); Log.e(LOG_TAG, "Disabled one percent hack due to: " + reason); } private Notification parseAlarmCursor(Cursor c) { Notification notification = new Notification(R.drawable.stat_notify_alarm, null, System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; String ringtone = c.getString(alarms.INDEX_RINGTONE); if (! ringtone.equals("")) notification.sound = android.net.Uri.parse(ringtone); if (c.getInt(alarms.INDEX_VIBRATE) == 1) if (mAudioManager.getRingerMode() != mAudioManager.RINGER_MODE_SILENT) /* I couldn't get the Notification to vibrate, so I do it myself... */ mVibrator.vibrate(new long[] {0, 200, 200, 400}, -1); if (c.getInt(alarms.INDEX_LIGHTS) == 1) { notification.flags |= Notification.FLAG_SHOW_LIGHTS; notification.defaults |= Notification.DEFAULT_LIGHTS; } return notification; } private String formatTime(Date d) { String format = android.provider.Settings.System.getString(getContentResolver(), android.provider.Settings.System.TIME_12_24); if (format == null || format.equals("12")) { return java.text.DateFormat.getTimeInstance(java.text.DateFormat.SHORT, java.util.Locale.getDefault()).format(d); } else { return (new java.text.SimpleDateFormat("HH:mm")).format(d); } } /* Old versions of Android (haven't experimented to determine exactly which are included), at least on the emulator, really don't want you to call reenableKeyguard() if you haven't first disabled it. So to stay compatible with older devices, let's add an extra setting and add this function. */ private void setEnablednessOfKeyguard(boolean enabled) { if (enabled) { if (keyguardDisabled) { kl.reenableKeyguard(); keyguardDisabled = false; } } else { if (! keyguardDisabled) { if (km.inKeyguardRestrictedInputMode()) { registerReceiver(mUserPresentReceiver, userPresent); } else { kl.disableKeyguard(); keyguardDisabled = true; } } } if (keyguardDisabled && settings.getBoolean(SettingsActivity.KEY_NOTIFY_WHEN_KG_DISABLED, true)) mNotificationManager.notify(NOTIFICATION_KG_UNLOCKED, kgUnlockedNotification); else mNotificationManager.cancel(NOTIFICATION_KG_UNLOCKED); } private final BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_USER_PRESENT.equals(intent.getAction())){ unregisterReceiver(mUserPresentReceiver); if (sp_store.getBoolean(KEY_DISABLE_LOCKING, false)) setEnablednessOfKeyguard(false); } } }; private void disconnectPlugin() { unbindService(pluginServiceConnection); stopService(pluginIntent); pluginServiceConnection.service = null; pluginPackage = "none"; } public void reloadSettings() { reloadSettings(false); } public void reloadSettings(boolean cancelFirst) { str = new Str(res); /* Language override may have changed */ if (cancelFirst) mNotificationManager.cancel(NOTIFICATION_PRIMARY); if (sp_store.getBoolean(KEY_DISABLE_LOCKING, false)) setEnablednessOfKeyguard(false); else setEnablednessOfKeyguard(true); //unregisterReceiver(mBatteryInfoReceiver); /* It appears that there's no need to unregister first */ registerReceiver(mBatteryInfoReceiver, batteryChanged); } public Boolean pluginHasSettings() { if (pluginServiceConnection.service == null) return false; try { Class<?> c = pluginServiceConnection.service.getClass(); java.lang.reflect.Method m = c.getMethod("hasSettings", EMPTY_CLASS_ARRAY); return (Boolean) m.invoke(pluginServiceConnection.service, EMPTY_OBJECT_ARRAY); } catch (Exception e) { e.printStackTrace(); return false; } } public void configurePlugin() { if (pluginServiceConnection.service == null) return; try { Class<?> c = pluginServiceConnection.service.getClass(); java.lang.reflect.Method m = c.getMethod("configure", EMPTY_CLASS_ARRAY); m.invoke(pluginServiceConnection.service, EMPTY_OBJECT_ARRAY); } catch (Exception e) { e.printStackTrace(); } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class AlarmDatabase { private static final String DATABASE_NAME = "alarms.db"; private static final int DATABASE_VERSION = 5; private static final String ALARM_TABLE_NAME = "alarms"; public static final String KEY_ID = "_id"; public static final String KEY_ENABLED = "enabled"; public static final String KEY_TYPE = "type"; public static final String KEY_THRESHOLD = "threshold"; public static final String KEY_RINGTONE = "ringtone"; public static final String KEY_VIBRATE = "vibrate"; public static final String KEY_LIGHTS = "lights"; /* Is this a safe practice, or do I need to use Cursor.getColumnIndexOrThrow()? */ public static final int INDEX_ID = 0; public static final int INDEX_ENABLED = 1; public static final int INDEX_TYPE = 2; public static final int INDEX_THRESHOLD = 3; public static final int INDEX_RINGTONE = 4; public static final int INDEX_VIBRATE = 5; public static final int INDEX_LIGHTS = 6; private final SQLOpenHelper mSQLOpenHelper; private SQLiteDatabase rdb; private SQLiteDatabase wdb; public AlarmDatabase(Context context) { mSQLOpenHelper = new SQLOpenHelper(context); rdb = mSQLOpenHelper.getReadableDatabase(); wdb = mSQLOpenHelper.getWritableDatabase(); } public void close() { rdb.close(); wdb.close(); } public Cursor getAllAlarms(Boolean reversed) { String order = "DESC"; if (reversed) order = "ASC"; return rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " ORDER BY " + KEY_ID + " " + order, null); } public Cursor getAlarm(int id) { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_ID + "=" + id + " LIMIT 1", null); c.moveToFirst(); return c; } public Boolean anyActiveAlarms() { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE ENABLED=1 LIMIT 1", null); Boolean b = (c.getCount() > 0); c.close(); return b; } public Cursor activeAlarmFull() { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_TYPE + "='fully_charged' AND ENABLED=1 LIMIT 1", null); if (c.getCount() == 0) { c.close(); return null; } c.moveToFirst(); return c; } public Cursor activeAlarmChargeDrops(int current, int previous) { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_TYPE + "='charge_drops' AND ENABLED=1 AND " + KEY_THRESHOLD + ">" + current + " AND " + KEY_THRESHOLD + "<=" + previous + " LIMIT 1", null); if (c.getCount() == 0) { c.close(); return null; } c.moveToFirst(); return c; } public Cursor activeAlarmChargeRises(int current, int previous) { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_TYPE + "='charge_rises' AND ENABLED=1 AND " + KEY_THRESHOLD + "<" + current + " AND " + KEY_THRESHOLD + ">=" + previous + " LIMIT 1", null); if (c.getCount() == 0) { c.close(); return null; } c.moveToFirst(); return c; } public Cursor activeAlarmTempRises(int current, int previous) { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_TYPE + "='temp_rises' AND ENABLED=1 AND " + KEY_THRESHOLD + "<" + current + " AND " + KEY_THRESHOLD + ">=" + previous + " LIMIT 1", null); if (c.getCount() == 0) { c.close(); return null; } c.moveToFirst(); return c; } public Cursor activeAlarmFailure() { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE "+ KEY_TYPE + "='health_failure' AND ENABLED=1 LIMIT 1", null); if (c.getCount() == 0) { c.close(); return null; } c.moveToFirst(); return c; } public void addAlarm(Boolean enabled, String type, String threshold, String ringtone, Boolean vibrate, Boolean lights) { wdb.execSQL("INSERT INTO " + ALARM_TABLE_NAME + " VALUES (NULL, " + (enabled ? 1 : 0) + " ," + "'" + type + "'" + " ," + "'" + threshold + "'" + " ," + "'" + ringtone + "'" + " ," + (vibrate ? 1 : 0) + " ," + (lights ? 1 : 0) + ")"); } public int addAlarm() { addAlarm(true, "fully_charged", "", android.provider.Settings.System.DEFAULT_NOTIFICATION_URI.toString(), false, true); Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE " + KEY_ID + "= last_insert_rowid()", null); c.moveToFirst(); int i = c.getInt(INDEX_ID); c.close(); return i; } public void setEnabled(int id, Boolean enabled) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_ENABLED + "=" + (enabled ? 1 : 0) + " WHERE " + KEY_ID + "=" + id); } public void setVibrate(int id, Boolean vibrate) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_VIBRATE + "=" + (vibrate ? 1 : 0) + " WHERE " + KEY_ID + "=" + id); } public void setLights(int id, Boolean lights) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_LIGHTS + "=" + (lights ? 1 : 0) + " WHERE " + KEY_ID + "=" + id); } public Boolean toggleEnabled(int id) { Cursor c = rdb.rawQuery("SELECT * FROM " + ALARM_TABLE_NAME + " WHERE " + KEY_ID + "=" + id, null); c.moveToFirst(); Boolean newEnabled = !(c.getInt(INDEX_ENABLED) == 1); c.close(); setEnabled(id, newEnabled); return newEnabled; } public void setType(int id, String type) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_TYPE + "='" + type + "' WHERE " + KEY_ID + "=" + id); } public void setThreshold(int id, String threshold) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_THRESHOLD + "='" + threshold + "' WHERE " + KEY_ID + "=" + id); } public void setRingtone(int id, String ringtone) { wdb.execSQL("UPDATE " + ALARM_TABLE_NAME + " SET " + KEY_RINGTONE + "='" + ringtone + "' WHERE " + KEY_ID + "=" + id); } public void deleteAlarm(int id) { wdb.execSQL("DELETE FROM " + ALARM_TABLE_NAME + " WHERE _id = " + id); } public void deleteAllAlarms() { mSQLOpenHelper.reset(); } private static class SQLOpenHelper extends SQLiteOpenHelper { public SQLOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + ALARM_TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_ENABLED + " INTEGER," + KEY_TYPE + " STRING," + KEY_THRESHOLD + " STRING," + KEY_RINGTONE + " STRING," + KEY_VIBRATE + " INTEGER," + KEY_LIGHTS + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (false) { } else { db.execSQL("DROP TABLE IF EXISTS " + ALARM_TABLE_NAME); onCreate(db); } } public void reset() { SQLiteDatabase db = getWritableDatabase(); db.execSQL("DROP TABLE IF EXISTS " + ALARM_TABLE_NAME); onCreate(db); } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class LogDatabase { private static final String DATABASE_NAME = "logs.db"; private static final int DATABASE_VERSION = 4; private static final String LOG_TABLE_NAME = "logs"; private static final String KEY_ID = "_id"; public static final String KEY_STATUS_CODE = "status"; public static final String KEY_CHARGE = "charge"; public static final String KEY_TIME = "time"; public static final String KEY_TEMPERATURE = "temperature"; public static final String KEY_VOLTAGE = "voltage"; public static final int STATUS_NEW = 0; public static final int STATUS_OLD = 1; private final SQLOpenHelper mSQLOpenHelper; private SQLiteDatabase rdb; private SQLiteDatabase wdb; public LogDatabase(Context context) { mSQLOpenHelper = new SQLOpenHelper(context); rdb = mSQLOpenHelper.getReadableDatabase(); wdb = mSQLOpenHelper.getWritableDatabase(); } public void close() { rdb.close(); wdb.close(); } public Cursor getAllLogs(Boolean reversed) { String order = "DESC"; if (reversed) order = "ASC"; return rdb.rawQuery("SELECT * FROM " + LOG_TABLE_NAME + " ORDER BY " + KEY_TIME + " " + order, null); } public void logStatus(int status, int plugged, int charge, int temp, int voltage, long time, int status_age) { Boolean duplicate = false; Cursor lastLog = rdb.rawQuery("SELECT * FROM " + LOG_TABLE_NAME + " ORDER BY " + KEY_TIME + " DESC LIMIT 1", null); if (lastLog.moveToFirst()){ int statusCode = lastLog.getInt(lastLog.getColumnIndexOrThrow(KEY_STATUS_CODE)); int lastCharge = lastLog.getInt(lastLog.getColumnIndexOrThrow(KEY_CHARGE)); int[] a = decodeStatus(statusCode); int lastStatus = a[0]; int lastPlugged = a[1]; if (charge == lastCharge && status == lastStatus && plugged == lastPlugged) duplicate = true; } if (! duplicate) wdb.execSQL("INSERT INTO " + LOG_TABLE_NAME + " VALUES (NULL, " + encodeStatus(status, plugged, status_age) + " ," + charge + " ," + time + " ," + temp + " ," + voltage + ")"); lastLog.close(); } public void prune(int max_hours) { long currentTM = System.currentTimeMillis(); long oldest_log = currentTM - ((long) max_hours * 60 * 60 * 1000); wdb.execSQL("DELETE FROM " + LOG_TABLE_NAME + " WHERE " + KEY_TIME + " < " + oldest_log); } /* My cursor adapter was getting a bit complicated since it could only see one datum at a time, and how I want to present the data depends on several interrelated factors. Storing all three of these items together simplifies things. */ private static int encodeStatus(int status, int plugged, int status_age) { return status + (plugged * 10) + (status_age * 100); } /* Returns [status, plugged, status_age] */ public static int[] decodeStatus(int statusCode) { int[] a = new int[3]; a[2] = statusCode / 100; statusCode -= a[2] * 100; a[1] = statusCode / 10; statusCode -= a[1] * 10; a[0] = statusCode; return a; } public void clearAllLogs() { mSQLOpenHelper.reset(); } private static class SQLOpenHelper extends SQLiteOpenHelper { public SQLOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + LOG_TABLE_NAME + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_STATUS_CODE + " INTEGER," + KEY_CHARGE + " INTEGER," + KEY_TIME + " INTEGER," + KEY_TEMPERATURE + " INTEGER," + KEY_VOLTAGE + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion == 3 && newVersion == 4) { db.execSQL("ALTER TABLE " + LOG_TABLE_NAME + " ADD COLUMN " + KEY_TEMPERATURE + " INTEGER;"); db.execSQL("ALTER TABLE " + LOG_TABLE_NAME + " ADD COLUMN " + KEY_VOLTAGE + " INTEGER;"); } else { db.execSQL("DROP TABLE IF EXISTS " + LOG_TABLE_NAME); onCreate(db); } } public void reset() { SQLiteDatabase db = getWritableDatabase(); db.execSQL("DROP TABLE IF EXISTS " + LOG_TABLE_NAME); onCreate(db); } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.database.DataSetObserver; import android.graphics.drawable.TransitionDrawable; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnCreateContextMenuListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class AlarmsActivity extends Activity { private AlarmDatabase alarms; private Resources res; private Context context; private Str str; private Cursor mCursor; private LayoutInflater mInflater; private LinearLayout mAlarmsList; private int curId; /* The alarm id for the View that was just long-pressed */ private TransitionDrawable curTrans = null; /* The currently active TransitionDrawable */ private int curIndex; /* The ViewGroup index of the currently focused item (to set focus after deletion) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); res = getResources(); str = new Str(res); // Stranglely disabled by default for API level 14+ ///*v11*/ if (res.getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); setContentView(R.layout.alarms); setWindowSubtitle(res.getString(R.string.alarm_settings)); alarms = new AlarmDatabase(context); //alarms.deleteAllAlarms(); mCursor = alarms.getAllAlarms(true); startManagingCursor(mCursor); mInflater = LayoutInflater.from(context); mAlarmsList = (LinearLayout) findViewById(R.id.alarms_list); populateList(); mCursor.registerDataSetObserver(new AlarmsObserver()); View addAlarm = findViewById(R.id.add_alarm); addAlarm.setOnClickListener(new OnClickListener() { public void onClick(View v) { int id = alarms.addAlarm(); ComponentName comp = new ComponentName(getPackageName(), AlarmEditActivity.class.getName()); startActivity(new Intent().setComponent(comp).putExtra(AlarmEditActivity.EXTRA_ALARM_ID, id)); } }); } private void setWindowSubtitle(String subtitle) { if (res.getBoolean(R.bool.long_activity_names)) setTitle(res.getString(R.string.app_full_name) + " - " + subtitle); else setTitle(subtitle); } private void populateList() { mAlarmsList.removeAllViews(); if (mCursor.moveToFirst()) { while (! mCursor.isAfterLast()) { View v = mInflater.inflate(R.layout.alarm_item , mAlarmsList, false); bindView(v); mAlarmsList.addView(v, mAlarmsList.getChildCount()); mCursor.moveToNext(); } } } @Override protected void onDestroy() { super.onDestroy(); mCursor.close(); alarms.close(); } @Override protected void onResume() { super.onResume(); mCursor.requery(); } @Override protected void onPause() { super.onPause(); mCursor.deactivate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.settings, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_help: ComponentName comp = new ComponentName(getPackageName(), SettingsHelpActivity.class.getName()); Intent intent = new Intent().setComponent(comp).putExtra(SettingsActivity.EXTRA_SCREEN, SettingsActivity.KEY_ALARM_SETTINGS); startActivity(intent); return true; case android.R.id.home: startActivity(new Intent(this, BatteryIndicator.class)); return true; default: return super.onOptionsItemSelected(item); } } @Override public boolean onContextItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.delete_alarm: alarms.deleteAlarm(curId); mCursor.requery(); int childCount = mAlarmsList.getChildCount(); if (curIndex < childCount) mAlarmsList.getChildAt(curIndex).findViewById(R.id.alarm_summary_box).requestFocus(); else if (childCount > 0) mAlarmsList.getChildAt(curIndex - 1).findViewById(R.id.alarm_summary_box).requestFocus(); return true; default: break; } return super.onContextItemSelected(item); } private class AlarmsObserver extends DataSetObserver { public AlarmsObserver(){ super(); } @Override public void onChanged() { super.onChanged(); populateList(); } } private TransitionDrawable castToTransitionDrawable(android.graphics.drawable.Drawable d) { try { return (TransitionDrawable) d; } catch (Exception e) { return null; } } private void bindView(View view) { final TextView summary_tv = (TextView) view.findViewById(R.id.alarm_summary); final View summary_box = view.findViewById(R.id.alarm_summary_box); final View indicator = view.findViewById(R.id.indicator); final ImageView barOnOff = (ImageView) indicator.findViewById(R.id.bar_onoff); final int id = mCursor.getInt (AlarmDatabase.INDEX_ID); String type = mCursor.getString(AlarmDatabase.INDEX_TYPE); String threshold = mCursor.getString(AlarmDatabase.INDEX_THRESHOLD); Boolean enabled = (mCursor.getInt(AlarmDatabase.INDEX_ENABLED) == 1); String s = str.alarm_types_display[str.indexOf(str.alarm_type_values, type)]; if (type.equals("temp_rises")) { Boolean convertF = android.preference.PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getBoolean(SettingsActivity.KEY_CONVERT_F, false); s += " " + str.formatTemp(Integer.valueOf(threshold), convertF, false); } else if (type.equals("charge_drops") || type.equals("charge_rises")) { s += " " + threshold + "%"; } final String summary = s; barOnOff.setImageResource(enabled ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off); summary_tv.setText(summary); indicator.setOnClickListener(new OnClickListener() { public void onClick(View v) { barOnOff.setImageResource(alarms.toggleEnabled(id) ? R.drawable.ic_indicator_on : R.drawable.ic_indicator_off); } }); summary_box.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { curId = id; curIndex = mAlarmsList.indexOfChild((View) v.getParent().getParent()); if (curTrans != null) { curTrans.resetTransition(); curTrans = null; } getMenuInflater().inflate(R.menu.alarm_item_context, menu); menu.setHeaderTitle(summary); } }); summary_box.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, android.view.MotionEvent m) { if (v.isPressed() && curTrans == null ) { curTrans = castToTransitionDrawable(v.getBackground().getCurrent()); if (curTrans != null) curTrans.startTransition(350); } else if (! v.isPressed() && curTrans != null) { curTrans.resetTransition(); curTrans = null; } return false; } }); summary_box.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, android.view.KeyEvent event) { if (keyCode == event.KEYCODE_DPAD_CENTER && event.getAction() == event.ACTION_DOWN) v.setPressed(true); if (v.isPressed() && curTrans == null) { curTrans = castToTransitionDrawable(v.getBackground().getCurrent()); if (curTrans != null) curTrans.startTransition(350); } else if (curTrans != null) { curTrans.resetTransition(); curTrans = null; } return false; } }); summary_box.setOnClickListener(new OnClickListener() { public void onClick(View v) { ComponentName comp = new ComponentName(getPackageName(), AlarmEditActivity.class.getName()); startActivity(new Intent().setComponent(comp).putExtra(AlarmEditActivity.EXTRA_ALARM_ID, id)); } }); } }
Java
/* Copyright (c) 2011 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; public class SharedPrefsBackupAgent extends BackupAgentHelper { @Override public void onCreate() { SharedPreferencesBackupHelper helper = new SharedPreferencesBackupHelper(this, "com.darshancomputing.BatteryIndicatorPro_preferences"); addHelper("key_shared_prefs", helper); } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.ComponentName; import android.content.ServiceConnection; import android.os.IBinder; public class BIServiceConnection implements ServiceConnection { public BatteryIndicatorService biService; public void onServiceConnected(ComponentName name, IBinder service) { biService = ((BatteryIndicatorService.LocalBinder) service).getService(); } public void onServiceDisconnected(ComponentName name) { biService = null; } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.PreferenceActivity; import android.preference.PreferenceGroup; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class AlarmEditActivity extends PreferenceActivity { private Resources res; private Context context; private Str str; private PreferenceScreen mPreferenceScreen; private SharedPreferences settings; private AlarmDatabase alarms; private Cursor mCursor; private AlarmAdapter mAdapter; public static final String KEY_ENABLED = "enabled"; public static final String KEY_TYPE = "type"; public static final String KEY_THRESHOLD = "threshold"; public static final String KEY_RINGTONE = "ringtone"; public static final String KEY_VIBRATE = "vibrate"; public static final String KEY_LIGHTS = "lights"; public static final String EXTRA_ALARM_ID = "com.darshancomputing.BatteryIndicatorPro.AlarmID"; private static final String[] chargeEntries = { "5%", "10%", "15%", "20%", "25%", "30%", "35%", "40%", "45%", "50%", "55%", "60%", "65%", "70%", "75%", "80%", "85%", "90%", "95%", "99%"}; private static final String[] chargeValues = { "5", "10", "15", "20", "25", "30", "35", "40", "45", "50", "55", "60", "65", "70", "75", "80", "85", "90", "95", "99"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = getApplicationContext(); res = getResources(); str = new Str(res); alarms = new AlarmDatabase(context); settings = PreferenceManager.getDefaultSharedPreferences(context); if (res.getBoolean(R.bool.override_list_activity_layout)) { setContentView(R.layout.list_activity); getListView().setDivider(res.getDrawable(R.drawable.my_divider)); } // Stranglely disabled by default for API level 14+ ///*v11*/ if (res.getBoolean(R.bool.api_level_14_plus)) ///*v11*/ getActionBar().setHomeButtonEnabled(true); mCursor = alarms.getAlarm(getIntent().getIntExtra(EXTRA_ALARM_ID, -1)); mAdapter = new AlarmAdapter(); setWindowSubtitle(res.getString(R.string.alarm_settings_subtitle)); addPreferencesFromResource(R.xml.alarm_pref_screen); mPreferenceScreen = getPreferenceScreen(); syncValuesAndSetListeners(); } private void setWindowSubtitle(String subtitle) { if (res.getBoolean(R.bool.long_activity_names)) setTitle(res.getString(R.string.app_full_name) + " - " + subtitle); else setTitle(subtitle); } @Override protected void onDestroy() { super.onDestroy(); mCursor.close(); alarms.close(); } @Override protected void onResume() { super.onResume(); mCursor.requery(); mCursor.moveToFirst(); mAdapter.requery(); } @Override protected void onPause() { super.onPause(); mCursor.deactivate(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.alarm_edit, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_delete: alarms.deleteAlarm(mAdapter.id); finish(); return true; case R.id.menu_help: ComponentName comp = new ComponentName(getPackageName(), SettingsHelpActivity.class.getName()); Intent intent = new Intent().setComponent(comp).putExtra(SettingsActivity.EXTRA_SCREEN, SettingsActivity.KEY_ALARM_EDIT_SETTINGS); startActivity(intent); return true; default: return super.onOptionsItemSelected(item); } } private void syncValuesAndSetListeners() { CheckBoxPreference cb = (CheckBoxPreference) mPreferenceScreen.findPreference(KEY_ENABLED); cb.setChecked(mAdapter.enabled); cb.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { mAdapter.setEnabled((Boolean) newValue); return true; } }); ListPreference lp = (ListPreference) mPreferenceScreen.findPreference(KEY_TYPE); lp.setValue(mAdapter.type); updateSummary(lp); lp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { if (mAdapter.type.equals((String) newValue)) return false; mAdapter.setType((String) newValue); ((ListPreference) pref).setValue((String) newValue); updateSummary((ListPreference) pref); setUpThresholdList(true); return false; } }); lp = (ListPreference) mPreferenceScreen.findPreference(KEY_THRESHOLD); setUpThresholdList(false); lp.setValue(mAdapter.threshold); updateSummary(lp); lp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { if (mAdapter.threshold.equals((String) newValue)) return false; mAdapter.setThreshold((String) newValue); ((ListPreference) pref).setValue((String) newValue); updateSummary((ListPreference) pref); return false; } }); AlarmRingtonePreference rp = (AlarmRingtonePreference) mPreferenceScreen.findPreference(KEY_RINGTONE); rp.setValue(mAdapter.ringtone); rp.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { if (mAdapter.ringtone.equals(newValue)) return false; mAdapter.setRingtone((String) newValue); ((AlarmRingtonePreference) pref).setValue((String) newValue); return false; } }); cb = (CheckBoxPreference) mPreferenceScreen.findPreference(KEY_VIBRATE); cb.setChecked(mAdapter.vibrate); cb.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { mAdapter.setVibrate((Boolean) newValue); return true; } }); cb = (CheckBoxPreference) mPreferenceScreen.findPreference(KEY_LIGHTS); cb.setChecked(mAdapter.lights); cb.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference pref, Object newValue) { mAdapter.setLights((Boolean) newValue); return true; } }); } private void updateSummary(ListPreference lp) { Boolean formatterUsed; lp.setSummary("%%"); if (lp.getSummary().length() == 2) formatterUsed = false; else formatterUsed = true; String entry = (String) lp.getEntry(); if (entry == null) entry = ""; if (formatterUsed) entry = entry.replace("%", "%%"); if (lp.isEnabled()) lp.setSummary(str.currently_set_to + entry); else lp.setSummary(str.alarm_pref_not_used); } private void setUpThresholdList(Boolean resetValue) { ListPreference lp = (ListPreference) mPreferenceScreen.findPreference(KEY_THRESHOLD); if (mAdapter.type.equals("temp_rises")) { lp.setEntries(str.temp_alarm_entries); lp.setEntryValues(str.temp_alarm_values); lp.setEnabled(true); if (resetValue) { mAdapter.setThreshold(str.temp_alarm_values[3]); lp.setValue(mAdapter.threshold); } } else if (mAdapter.type.equals("charge_drops") || mAdapter.type.equals("charge_rises")) { lp.setEntries(chargeEntries); lp.setEntryValues(chargeValues); lp.setEnabled(true); if (resetValue) { if (mAdapter.type.equals("charge_drops")) mAdapter.setThreshold("20"); else mAdapter.setThreshold("90"); lp.setValue(mAdapter.threshold); } } else { lp.setEnabled(false); } updateSummary(lp); } private class AlarmAdapter { public int id; public String type, threshold, ringtone; public Boolean enabled, vibrate, lights; public AlarmAdapter() { requery(); } public void requery() { id = mCursor.getInt (AlarmDatabase.INDEX_ID); type = mCursor.getString(AlarmDatabase.INDEX_TYPE); threshold = mCursor.getString(AlarmDatabase.INDEX_THRESHOLD); ringtone = mCursor.getString(AlarmDatabase.INDEX_RINGTONE); enabled = (mCursor.getInt(AlarmDatabase.INDEX_ENABLED) == 1); vibrate = (mCursor.getInt(AlarmDatabase.INDEX_VIBRATE) == 1); lights = (mCursor.getInt(AlarmDatabase.INDEX_LIGHTS) == 1); } public void setEnabled(Boolean b) { enabled = b; alarms.setEnabled(id, enabled); } public void setVibrate(Boolean b) { vibrate = b; alarms.setVibrate(id, vibrate); } public void setLights(Boolean b) { lights = b; alarms.setLights(id, lights); } public void setType(String s) { type = s; alarms.setType(id, type); } public void setThreshold(String s) { threshold = s; alarms.setThreshold(id, threshold); } public void setRingtone(String s) { ringtone = s; alarms.setRingtone(id, ringtone); } } }
Java
/* Copyright (c) 2010 Josiah Barber (aka Darshan) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. */ package com.darshancomputing.BatteryIndicatorPro; import android.content.Context; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class ColorPreviewPreference extends Preference { public int redThresh; public int amberThresh; public int greenThresh; public ColorPreviewPreference(Context context) { super(context); } public ColorPreviewPreference(Context context, AttributeSet attrs) { super(context, attrs); } public ColorPreviewPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected View onCreateView(ViewGroup parent){ return super.onCreateView(parent); } @Override protected void onBindView (View view) { super.onBindView(view); ImageView iv = (ImageView) view.findViewById(R.id.color_preview_bar_v); if (iv == null) return; LayerDrawable ld = (LayerDrawable) iv.getDrawable(); for (int i = 0; i < 20; i++) { if (redThresh > i*5) ld.getDrawable(i).setLevel(1); else if (amberThresh > i*5) ld.getDrawable(i).setLevel(2); else if (greenThresh <= i*5) ld.getDrawable(i).setLevel(3); } } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { public static final String EXTRA_MESSAGE = "message"; public static final String PROPERTY_REG_ID = "registration_id"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000; /** * Substitute you own sender ID here. This is the project number you got * from the API Console, as described in "Getting Started." */ String SENDER_ID = "Your-Sender-ID"; /** * Tag used on log messages. */ static final String TAG = "GCM Demo"; TextView mDisplay; GoogleCloudMessaging gcm; AtomicInteger msgId = new AtomicInteger(); Context context; String regid; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); context = getApplicationContext(); // Check device for Play Services APK. If check succeeds, proceed with GCM registration. if (checkPlayServices()) { gcm = GoogleCloudMessaging.getInstance(this); regid = getRegistrationId(context); if (regid.isEmpty()) { registerInBackground(); } } else { Log.i(TAG, "No valid Google Play Services APK found."); } } @Override protected void onResume() { super.onResume(); // Check device for Play Services APK. checkPlayServices(); } /** * Check the device to make sure it has the Google Play Services APK. If * it doesn't, display a dialog that allows users to download the APK from * the Google Play Store or enable it in the device's system settings. */ private boolean checkPlayServices() { int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (resultCode != ConnectionResult.SUCCESS) { if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show(); } else { Log.i(TAG, "This device is not supported."); finish(); } return false; } return true; } /** * Stores the registration ID and the app versionCode in the application's * {@code SharedPreferences}. * * @param context application's context. * @param regId registration ID */ private void storeRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGcmPreferences(context); int appVersion = getAppVersion(context); Log.i(TAG, "Saving regId on app version " + appVersion); SharedPreferences.Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); } /** * Gets the current registration ID for application on GCM service, if there is one. * <p> * If result is empty, the app needs to register. * * @return registration ID, or empty string if there is no existing * registration ID. */ private String getRegistrationId(Context context) { final SharedPreferences prefs = getGcmPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); if (registrationId.isEmpty()) { Log.i(TAG, "Registration not found."); return ""; } // Check if app was updated; if so, it must clear the registration ID // since the existing regID is not guaranteed to work with the new // app version. int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int currentVersion = getAppVersion(context); if (registeredVersion != currentVersion) { Log.i(TAG, "App version changed."); return ""; } return registrationId; } /** * Registers the application with GCM servers asynchronously. * <p> * Stores the registration ID and the app versionCode in the application's * shared preferences. */ private void registerInBackground() { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging.getInstance(context); } regid = gcm.register(SENDER_ID); msg = "Device registered, registration ID=" + regid; // You should send the registration ID to your server over HTTP, so it // can use GCM/HTTP or CCS to send messages to your app. sendRegistrationIdToBackend(); // For this demo: we don't need to send it because the device will send // upstream messages to a server that echo back the message using the // 'from' address in the message. // Persist the regID - no need to register again. storeRegistrationId(context, regid); } catch (IOException ex) { msg = "Error :" + ex.getMessage(); // If there is an error, don't just keep trying to register. // Require the user to click a button again, or perform // exponential back-off. } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } // Send an upstream message. public void onClick(final View view) { if (view == findViewById(R.id.send)) { new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { String msg = ""; try { Bundle data = new Bundle(); data.putString("my_message", "Hello World"); data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW"); String id = Integer.toString(msgId.incrementAndGet()); gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data); msg = "Sent message"; } catch (IOException ex) { msg = "Error :" + ex.getMessage(); } return msg; } @Override protected void onPostExecute(String msg) { mDisplay.append(msg + "\n"); } }.execute(null, null, null); } else if (view == findViewById(R.id.clear)) { mDisplay.setText(""); } } @Override protected void onDestroy() { super.onDestroy(); } /** * @return Application's version code from the {@code PackageManager}. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Could not get package name: " + e); } } /** * @return Application's {@code SharedPreferences}. */ private SharedPreferences getGcmPreferences(Context context) { // This sample app persists the registration ID in shared preferences, but // how you store the regID in your app is up to you. return getSharedPreferences(DemoActivity.class.getSimpleName(), Context.MODE_PRIVATE); } /** * Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send * messages to your app. Not needed for this demo since the device sends upstream messages * to a server that echoes back the message using the 'from' address in the message. */ private void sendRegistrationIdToBackend() { // Your implementation here. } }
Java
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.support.v4.content.WakefulBroadcastReceiver; /** * This {@code WakefulBroadcastReceiver} takes care of creating and managing a * partial wake lock for your app. It passes off the work of processing the GCM * message to an {@code IntentService}, while ensuring that the device does not * go back to sleep in the transition. The {@code IntentService} calls * {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to * release the wake lock. */ public class GcmBroadcastReceiver extends WakefulBroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Explicitly specify that GcmIntentService will handle the intent. ComponentName comp = new ComponentName(context.getPackageName(), GcmIntentService.class.getName()); // Start the service, keeping the device awake while it is launching. startWakefulService(context, (intent.setComponent(comp))); setResultCode(Activity.RESULT_OK); } }
Java
/* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import com.google.android.gms.gcm.GoogleCloudMessaging; import android.app.IntentService; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.v4.app.NotificationCompat; import android.util.Log; /** * This {@code IntentService} does the actual handling of the GCM message. * {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a * partial wake lock for this service while the service does its work. When the * service is finished, it calls {@code completeWakefulIntent()} to release the * wake lock. */ public class GcmIntentService extends IntentService { public static final int NOTIFICATION_ID = 1; private NotificationManager mNotificationManager; NotificationCompat.Builder builder; public GcmIntentService() { super("GcmIntentService"); } public static final String TAG = "GCM Demo"; @Override protected void onHandleIntent(Intent intent) { Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); // The getMessageType() intent parameter must be the intent you received // in your BroadcastReceiver. String messageType = gcm.getMessageType(intent); if (!extras.isEmpty()) { // has effect of unparcelling Bundle /* * Filter messages based on message type. Since it is likely that GCM will be * extended in the future with new message types, just ignore any message types you're * not interested in, or that you don't recognize. */ if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { sendNotification("Send error: " + extras.toString()); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { sendNotification("Deleted messages on server: " + extras.toString()); // If it's a regular GCM message, do some work. } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // This loop represents the service doing some work. for (int i = 0; i < 5; i++) { Log.i(TAG, "Working... " + (i + 1) + "/5 @ " + SystemClock.elapsedRealtime()); try { Thread.sleep(5000); } catch (InterruptedException e) { } } Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime()); // Post notification of received message. sendNotification("Received: " + extras.toString()); Log.i(TAG, "Received: " + extras.toString()); } } // Release the wake lock provided by the WakefulBroadcastReceiver. GcmBroadcastReceiver.completeWakefulIntent(intent); } // Put the message into a notification and post it. // This is just one simple example of what you might choose to do with // a GCM message. private void sendNotification(String msg) { mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, DemoActivity.class), 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_gcm) .setContentTitle("GCM Notification") .setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .setContentText(msg); mBuilder.setContentIntent(contentIntent); mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.IOException; /** * Exception thrown when GCM returned an error due to an invalid request. * <p> * This is equivalent to GCM posts that return an HTTP error different of 200. */ public final class InvalidRequestException extends IOException { private final int status; private final String description; public InvalidRequestException(int status) { this(status, null); } public InvalidRequestException(int status, String description) { super(getMessage(status, description)); this.status = status; this.description = description; } private static String getMessage(int status, String description) { StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status); if (description != null) { base.append("(").append(description).append(")"); } return base.toString(); } /** * Gets the HTTP Status Code. */ public int getHttpStatusCode() { return status; } /** * Gets the error description. */ public String getDescription() { return description; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; /** * Result of a GCM message request that returned HTTP status code 200. * * <p> * If the message is successfully created, the {@link #getMessageId()} returns * the message id and {@link #getErrorCodeName()} returns {@literal null}; * otherwise, {@link #getMessageId()} returns {@literal null} and * {@link #getErrorCodeName()} returns the code of the error. * * <p> * There are cases when a request is accept and the message successfully * created, but GCM has a canonical registration id for that device. In this * case, the server should update the registration id to avoid rejected requests * in the future. * * <p> * In a nutshell, the workflow to handle a result is: * <pre> * - Call {@link #getMessageId()}: * - {@literal null} means error, call {@link #getErrorCodeName()} * - non-{@literal null} means the message was created: * - Call {@link #getCanonicalRegistrationId()} * - if it returns {@literal null}, do nothing. * - otherwise, update the server datastore with the new id. * </pre> */ public final class Result implements Serializable { private final String messageId; private final String canonicalRegistrationId; private final String errorCode; public static final class Builder { // optional parameters private String messageId; private String canonicalRegistrationId; private String errorCode; public Builder canonicalRegistrationId(String value) { canonicalRegistrationId = value; return this; } public Builder messageId(String value) { messageId = value; return this; } public Builder errorCode(String value) { errorCode = value; return this; } public Result build() { return new Result(this); } } private Result(Builder builder) { canonicalRegistrationId = builder.canonicalRegistrationId; messageId = builder.messageId; errorCode = builder.errorCode; } /** * Gets the message id, if any. */ public String getMessageId() { return messageId; } /** * Gets the canonical registration id, if any. */ public String getCanonicalRegistrationId() { return canonicalRegistrationId; } /** * Gets the error code, if any. */ public String getErrorCodeName() { return errorCode; } @Override public String toString() { StringBuilder builder = new StringBuilder("["); if (messageId != null) { builder.append(" messageId=").append(messageId); } if (canonicalRegistrationId != null) { builder.append(" canonicalRegistrationId=") .append(canonicalRegistrationId); } if (errorCode != null) { builder.append(" errorCode=").append(errorCode); } return builder.append(" ]").toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT; import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS; import static com.google.android.gcm.server.Constants.JSON_ERROR; import static com.google.android.gcm.server.Constants.JSON_FAILURE; import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID; import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID; import static com.google.android.gcm.server.Constants.JSON_PAYLOAD; import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS; import static com.google.android.gcm.server.Constants.JSON_RESULTS; import static com.google.android.gcm.server.Constants.JSON_SUCCESS; import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY; import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE; import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN; import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX; import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID; import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME; import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE; import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID; import static com.google.android.gcm.server.Constants.TOKEN_ERROR; import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID; import com.google.android.gcm.server.Result.Builder; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.logging.Level; import java.util.logging.Logger; /** * Helper class to send messages to the GCM service using an API Key. */ public class Sender { protected static final String UTF8 = "UTF-8"; /** * Initial delay before first retry, without jitter. */ protected static final int BACKOFF_INITIAL_DELAY = 1000; /** * Maximum delay before a retry. */ protected static final int MAX_BACKOFF_DELAY = 1024000; protected final Random random = new Random(); protected static final Logger logger = Logger.getLogger(Sender.class.getName()); private final String key; /** * Default constructor. * * @param key API key obtained through the Google API Console. */ public Sender(String key) { this.key = nonNull(key); } /** * Sends a message to one device, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent, including the device's registration id. * @param registrationId device where the message will be sent. * @param retries number of retries in case of service unavailability errors. * * @return result of the request (see its javadoc for more details). * * @throws IllegalArgumentException if registrationId is {@literal null}. * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IOException if message could not be sent. */ public Result send(Message message, String registrationId, int retries) throws IOException { int attempt = 0; Result result = null; int backoff = BACKOFF_INITIAL_DELAY; boolean tryAgain; do { attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + registrationId); } result = sendNoRetry(message, registrationId); tryAgain = result == null && attempt <= retries; if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (result == null) { throw new IOException("Could not send message after " + attempt + " attempts"); } return result; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail. * * @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status. * @throws IllegalArgumentException if registrationId is {@literal null}. */ public Result sendNoRetry(Message message, String registrationId) throws IOException { StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId); Boolean delayWhileIdle = message.isDelayWhileIdle(); if (delayWhileIdle != null) { addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0"); } Boolean dryRun = message.isDryRun(); if (dryRun != null) { addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0"); } String collapseKey = message.getCollapseKey(); if (collapseKey != null) { addParameter(body, PARAM_COLLAPSE_KEY, collapseKey); } String restrictedPackageName = message.getRestrictedPackageName(); if (restrictedPackageName != null) { addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName); } Integer timeToLive = message.getTimeToLive(); if (timeToLive != null) { addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive)); } for (Entry<String, String> entry : message.getData().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key == null || value == null) { logger.warning("Ignoring payload entry thas has null: " + entry); } else { key = PARAM_PAYLOAD_PREFIX + key; addParameter(body, key, URLEncoder.encode(value, UTF8)); } } String requestBody = body.toString(); logger.finest("Request body: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } if (status / 100 == 5) { logger.fine("GCM service is unavailable (status " + status + ")"); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("Plain post error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } else { try { responseBody = getAndClose(conn.getInputStream()); } catch (IOException e) { logger.log(Level.WARNING, "Exception reading response: ", e); // return null so it can retry return null; } } String[] lines = responseBody.split("\n"); if (lines.length == 0 || lines[0].equals("")) { throw new IOException("Received empty response from GCM service."); } String firstLine = lines[0]; String[] responseParts = split(firstLine); String token = responseParts[0]; String value = responseParts[1]; if (token.equals(TOKEN_MESSAGE_ID)) { Builder builder = new Result.Builder().messageId(value); // check for canonical registration id if (lines.length > 1) { String secondLine = lines[1]; responseParts = split(secondLine); token = responseParts[0]; value = responseParts[1]; if (token.equals(TOKEN_CANONICAL_REG_ID)) { builder.canonicalRegistrationId(value); } else { logger.warning("Invalid response from GCM: " + responseBody); } } Result result = builder.build(); if (logger.isLoggable(Level.FINE)) { logger.fine("Message created succesfully (" + result + ")"); } return result; } else if (token.equals(TOKEN_ERROR)) { return new Result.Builder().errorCode(value).build(); } else { throw new IOException("Invalid response from GCM: " + responseBody); } } /** * Sends a message to many devices, retrying in case of unavailability. * * <p> * <strong>Note: </strong> this method uses exponential back-off to retry in * case of service unavailability and hence could block the calling thread * for many seconds. * * @param message message to be sent. * @param regIds registration id of the devices that will receive * the message. * @param retries number of retries in case of service unavailability errors. * * @return combined result of all requests made. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 or 503 status. * @throws IOException if message could not be sent. */ public MulticastResult send(Message message, List<String> regIds, int retries) throws IOException { int attempt = 0; MulticastResult multicastResult; int backoff = BACKOFF_INITIAL_DELAY; // Map of results by registration id, it will be updated after each attempt // to send the messages Map<String, Result> results = new HashMap<String, Result>(); List<String> unsentRegIds = new ArrayList<String>(regIds); boolean tryAgain; List<Long> multicastIds = new ArrayList<Long>(); do { multicastResult = null; attempt++; if (logger.isLoggable(Level.FINE)) { logger.fine("Attempt #" + attempt + " to send message " + message + " to regIds " + unsentRegIds); } try { multicastResult = sendNoRetry(message, unsentRegIds); } catch(IOException e) { // no need for WARNING since exception might be already logged logger.log(Level.FINEST, "IOException on attempt " + attempt, e); } if (multicastResult != null) { long multicastId = multicastResult.getMulticastId(); logger.fine("multicast_id on attempt # " + attempt + ": " + multicastId); multicastIds.add(multicastId); unsentRegIds = updateStatus(unsentRegIds, results, multicastResult); tryAgain = !unsentRegIds.isEmpty() && attempt <= retries; } else { tryAgain = attempt <= retries; } if (tryAgain) { int sleepTime = backoff / 2 + random.nextInt(backoff); sleep(sleepTime); if (2 * backoff < MAX_BACKOFF_DELAY) { backoff *= 2; } } } while (tryAgain); if (multicastIds.isEmpty()) { // all JSON posts failed due to GCM unavailability throw new IOException("Could not post JSON requests to GCM after " + attempt + " attempts"); } // calculate summary int success = 0, failure = 0 , canonicalIds = 0; for (Result result : results.values()) { if (result.getMessageId() != null) { success++; if (result.getCanonicalRegistrationId() != null) { canonicalIds++; } } else { failure++; } } // build a new object with the overall result long multicastId = multicastIds.remove(0); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId).retryMulticastIds(multicastIds); // add results, in the same order as the input for (String regId : regIds) { Result result = results.get(regId); builder.addResult(result); } return builder.build(); } /** * Updates the status of the messages sent to devices and the list of devices * that should be retried. * * @param unsentRegIds list of devices that are still pending an update. * @param allResults map of status that will be updated. * @param multicastResult result of the last multicast sent. * * @return updated version of devices that should be retried. */ private List<String> updateStatus(List<String> unsentRegIds, Map<String, Result> allResults, MulticastResult multicastResult) { List<Result> results = multicastResult.getResults(); if (results.size() != unsentRegIds.size()) { // should never happen, unless there is a flaw in the algorithm throw new RuntimeException("Internal error: sizes do not match. " + "currentResults: " + results + "; unsentRegIds: " + unsentRegIds); } List<String> newUnsentRegIds = new ArrayList<String>(); for (int i = 0; i < unsentRegIds.size(); i++) { String regId = unsentRegIds.get(i); Result result = results.get(i); allResults.put(regId, result); String error = result.getErrorCodeName(); if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE) || error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) { newUnsentRegIds.add(regId); } } return newUnsentRegIds; } /** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, List, int)} for more info. * * @return multicast results if the message was sent successfully, * {@literal null} if it failed but could be retried. * * @throws IllegalArgumentException if registrationIds is {@literal null} or * empty. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IOException if there was a JSON parsing error */ public MulticastResult sendNoRetry(Message message, List<String> registrationIds) throws IOException { if (nonNull(registrationIds).isEmpty()) { throw new IllegalArgumentException("registrationIds cannot be empty"); } Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive()); setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey()); setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName()); setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE, message.isDelayWhileIdle()); setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun()); jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds); Map<String, String> payload = message.getData(); if (!payload.isEmpty()) { jsonRequest.put(JSON_PAYLOAD, payload); } String requestBody = JSONValue.toJSONString(jsonRequest); logger.finest("JSON request: " + requestBody); HttpURLConnection conn; int status; try { conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody); status = conn.getResponseCode(); } catch (IOException e) { logger.log(Level.FINE, "IOException posting to GCM", e); return null; } String responseBody; if (status != 200) { try { responseBody = getAndClose(conn.getErrorStream()); logger.finest("JSON error response: " + responseBody); } catch (IOException e) { // ignore the exception since it will thrown an InvalidRequestException // anyways responseBody = "N/A"; logger.log(Level.FINE, "Exception reading response: ", e); } throw new InvalidRequestException(status, responseBody); } try { responseBody = getAndClose(conn.getInputStream()); } catch(IOException e) { logger.log(Level.WARNING, "IOException reading response", e); return null; } logger.finest("JSON response: " + responseBody); JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue(); long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue(); MulticastResult.Builder builder = new MulticastResult.Builder(success, failure, canonicalIds, multicastId); @SuppressWarnings("unchecked") List<Map<String, Object>> results = (List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS); if (results != null) { for (Map<String, Object> jsonResult : results) { String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); Result result = new Result.Builder() .messageId(messageId) .canonicalRegistrationId(canonicalRegId) .errorCode(error) .build(); builder.addResult(result); } } MulticastResult multicastResult = builder.build(); return multicastResult; } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } } private IOException newIoException(String responseBody, Exception e) { // log exception, as IOException constructor that takes a message and cause // is only available on Java 6 String msg = "Error parsing JSON response (" + responseBody + ")"; logger.log(Level.WARNING, msg, e); return new IOException(msg + ":" + e); } private static void close(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // ignore error logger.log(Level.FINEST, "IOException closing stream", e); } } } /** * Sets a JSON field, but only if the value is not {@literal null}. */ private void setJsonField(Map<Object, Object> json, String field, Object value) { if (value != null) { json.put(field, value); } } private Number getNumber(Map<?, ?> json, String field) { Object value = json.get(field); if (value == null) { throw new CustomParserException("Missing field: " + field); } if (!(value instanceof Number)) { throw new CustomParserException("Field " + field + " does not contain a number: " + value); } return (Number) value; } class CustomParserException extends RuntimeException { CustomParserException(String message) { super(message); } } private String[] split(String line) throws IOException { String[] split = line.split("=", 2); if (split.length != 2) { throw new IOException("Received invalid response line from GCM: " + line); } return split; } /** * Make an HTTP post to a given URL. * * @return HTTP response. */ protected HttpURLConnection post(String url, String body) throws IOException { return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body); } /** * Makes an HTTP POST request to a given endpoint. * * <p> * <strong>Note: </strong> the returned connected should not be disconnected, * otherwise it would kill persistent connections made using Keep-Alive. * * @param url endpoint to post the request. * @param contentType type of request. * @param body body of the request. * * @return the underlying connection. * * @throws IOException propagated from underlying methods. */ protected HttpURLConnection post(String url, String contentType, String body) throws IOException { if (url == null || body == null) { throw new IllegalArgumentException("arguments cannot be null"); } if (!url.startsWith("https://")) { logger.warning("URL does not use https: " + url); } logger.fine("Sending POST to " + url); logger.finest("POST body: " + body); byte[] bytes = body.getBytes(); HttpURLConnection conn = getConnection(url); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", contentType); conn.setRequestProperty("Authorization", "key=" + key); OutputStream out = conn.getOutputStream(); try { out.write(bytes); } finally { close(out); } return conn; } /** * Creates a map with just one key-value pair. */ protected static final Map<String, String> newKeyValues(String key, String value) { Map<String, String> keyValues = new HashMap<String, String>(1); keyValues.put(nonNull(key), nonNull(value)); return keyValues; } /** * Creates a {@link StringBuilder} to be used as the body of an HTTP POST. * * @param name initial parameter for the POST. * @param value initial value for that parameter. * @return StringBuilder to be used an HTTP POST body. */ protected static StringBuilder newBody(String name, String value) { return new StringBuilder(nonNull(name)).append('=').append(nonNull(value)); } /** * Adds a new parameter to the HTTP POST body. * * @param body HTTP POST body. * @param name parameter's name. * @param value parameter's value. */ protected static void addParameter(StringBuilder body, String name, String value) { nonNull(body).append('&') .append(nonNull(name)).append('=').append(nonNull(value)); } /** * Gets an {@link HttpURLConnection} given an URL. */ protected HttpURLConnection getConnection(String url) throws IOException { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); return conn; } /** * Convenience method to convert an InputStream to a String. * <p> * If the stream ends in a newline character, it will be stripped. * <p> * If the stream is {@literal null}, returns an empty string. */ protected static String getString(InputStream stream) throws IOException { if (stream == null) { return ""; } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder content = new StringBuilder(); String newLine; do { newLine = reader.readLine(); if (newLine != null) { content.append(newLine).append('\n'); } } while (newLine != null); if (content.length() > 0) { // strip last newline content.setLength(content.length() - 1); } return content.toString(); } private static String getAndClose(InputStream stream) throws IOException { try { return getString(stream); } finally { if (stream != null) { close(stream); } } } static <T> T nonNull(T argument) { if (argument == null) { throw new IllegalArgumentException("argument cannot be null"); } return argument; } void sleep(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; /** * Constants used on GCM service communication. */ public final class Constants { /** * Endpoint for sending messages. */ public static final String GCM_SEND_ENDPOINT = "https://android.googleapis.com/gcm/send"; /** * HTTP parameter for registration id. */ public static final String PARAM_REGISTRATION_ID = "registration_id"; /** * HTTP parameter for collapse key. */ public static final String PARAM_COLLAPSE_KEY = "collapse_key"; /** * HTTP parameter for delaying the message delivery if the device is idle. */ public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle"; /** * HTTP parameter for telling gcm to validate the message without actually sending it. */ public static final String PARAM_DRY_RUN = "dry_run"; /** * HTTP parameter for package name that can be used to restrict message delivery by matching * against the package name used to generate the registration id. */ public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name"; /** * Prefix to HTTP parameter used to pass key-values in the message payload. */ public static final String PARAM_PAYLOAD_PREFIX = "data."; /** * Prefix to HTTP parameter used to set the message time-to-live. */ public static final String PARAM_TIME_TO_LIVE = "time_to_live"; /** * Too many messages sent by the sender. Retry after a while. */ public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded"; /** * Too many messages sent by the sender to a specific device. * Retry after a while. */ public static final String ERROR_DEVICE_QUOTA_EXCEEDED = "DeviceQuotaExceeded"; /** * Missing registration_id. * Sender should always add the registration_id to the request. */ public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration"; /** * Bad registration_id. Sender should remove this registration_id. */ public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration"; /** * The sender_id contained in the registration_id does not match the * sender_id used to register with the GCM servers. */ public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId"; /** * The user has uninstalled the application or turned off notifications. * Sender should stop sending messages to this device and delete the * registration_id. The client needs to re-register with the GCM servers to * receive notifications again. */ public static final String ERROR_NOT_REGISTERED = "NotRegistered"; /** * The payload of the message is too big, see the limitations. * Reduce the size of the message. */ public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig"; /** * Collapse key is required. Include collapse key in the request. */ public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey"; /** * A particular message could not be sent because the GCM servers were not * available. Used only on JSON requests, as in plain text requests * unavailability is indicated by a 503 response. */ public static final String ERROR_UNAVAILABLE = "Unavailable"; /** * A particular message could not be sent because the GCM servers encountered * an error. Used only on JSON requests, as in plain text requests internal * errors are indicated by a 500 response. */ public static final String ERROR_INTERNAL_SERVER_ERROR = "InternalServerError"; /** * Time to Live value passed is less than zero or more than maximum. */ public static final String ERROR_INVALID_TTL= "InvalidTtl"; /** * Token returned by GCM when a message was successfully sent. */ public static final String TOKEN_MESSAGE_ID = "id"; /** * Token returned by GCM when the requested registration id has a canonical * value. */ public static final String TOKEN_CANONICAL_REG_ID = "registration_id"; /** * Token returned by GCM when there was an error sending a message. */ public static final String TOKEN_ERROR = "Error"; /** * JSON-only field representing the registration ids. */ public static final String JSON_REGISTRATION_IDS = "registration_ids"; /** * JSON-only field representing the payload data. */ public static final String JSON_PAYLOAD = "data"; /** * JSON-only field representing the number of successful messages. */ public static final String JSON_SUCCESS = "success"; /** * JSON-only field representing the number of failed messages. */ public static final String JSON_FAILURE = "failure"; /** * JSON-only field representing the number of messages with a canonical * registration id. */ public static final String JSON_CANONICAL_IDS = "canonical_ids"; /** * JSON-only field representing the id of the multicast request. */ public static final String JSON_MULTICAST_ID = "multicast_id"; /** * JSON-only field representing the result of each individual request. */ public static final String JSON_RESULTS = "results"; /** * JSON-only field representing the error field of an individual request. */ public static final String JSON_ERROR = "error"; /** * JSON-only field sent by GCM when a message was successfully sent. */ public static final String JSON_MESSAGE_ID = "message_id"; private Constants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; /** * GCM message. * * <p> * Instances of this class are immutable and should be created using a * {@link Builder}. Examples: * * <strong>Simplest message:</strong> * <pre><code> * Message message = new Message.Builder().build(); * </pre></code> * * <strong>Message with optional attributes:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .build(); * </pre></code> * * <strong>Message with optional attributes and payload data:</strong> * <pre><code> * Message message = new Message.Builder() * .collapseKey(collapseKey) * .timeToLive(3) * .delayWhileIdle(true) * .dryRun(true) * .restrictedPackageName(restrictedPackageName) * .addData("key1", "value1") * .addData("key2", "value2") * .build(); * </pre></code> */ public final class Message implements Serializable { private final String collapseKey; private final Boolean delayWhileIdle; private final Integer timeToLive; private final Map<String, String> data; private final Boolean dryRun; private final String restrictedPackageName; public static final class Builder { private final Map<String, String> data; // optional parameters private String collapseKey; private Boolean delayWhileIdle; private Integer timeToLive; private Boolean dryRun; private String restrictedPackageName; public Builder() { this.data = new LinkedHashMap<String, String>(); } /** * Sets the collapseKey property. */ public Builder collapseKey(String value) { collapseKey = value; return this; } /** * Sets the delayWhileIdle property (default value is {@literal false}). */ public Builder delayWhileIdle(boolean value) { delayWhileIdle = value; return this; } /** * Sets the time to live, in seconds. */ public Builder timeToLive(int value) { timeToLive = value; return this; } /** * Adds a key/value pair to the payload data. */ public Builder addData(String key, String value) { data.put(key, value); return this; } /** * Sets the dryRun property (default value is {@literal false}). */ public Builder dryRun(boolean value) { dryRun = value; return this; } /** * Sets the restrictedPackageName property. */ public Builder restrictedPackageName(String value) { restrictedPackageName = value; return this; } public Message build() { return new Message(this); } } private Message(Builder builder) { collapseKey = builder.collapseKey; delayWhileIdle = builder.delayWhileIdle; data = Collections.unmodifiableMap(builder.data); timeToLive = builder.timeToLive; dryRun = builder.dryRun; restrictedPackageName = builder.restrictedPackageName; } /** * Gets the collapse key. */ public String getCollapseKey() { return collapseKey; } /** * Gets the delayWhileIdle flag. */ public Boolean isDelayWhileIdle() { return delayWhileIdle; } /** * Gets the time to live (in seconds). */ public Integer getTimeToLive() { return timeToLive; } /** * Gets the dryRun flag. */ public Boolean isDryRun() { return dryRun; } /** * Gets the restricted package name. */ public String getRestrictedPackageName() { return restrictedPackageName; } /** * Gets the payload data, which is immutable. */ public Map<String, String> getData() { return data; } @Override public String toString() { StringBuilder builder = new StringBuilder("Message("); if (collapseKey != null) { builder.append("collapseKey=").append(collapseKey).append(", "); } if (timeToLive != null) { builder.append("timeToLive=").append(timeToLive).append(", "); } if (delayWhileIdle != null) { builder.append("delayWhileIdle=").append(delayWhileIdle).append(", "); } if (dryRun != null) { builder.append("dryRun=").append(dryRun).append(", "); } if (restrictedPackageName != null) { builder.append("restrictedPackageName=").append(restrictedPackageName).append(", "); } if (!data.isEmpty()) { builder.append("data: {"); for (Map.Entry<String, String> entry : data.entrySet()) { builder.append(entry.getKey()).append("=").append(entry.getValue()) .append(","); } builder.delete(builder.length() - 1, builder.length()); builder.append("}"); } if (builder.charAt(builder.length() - 1) == ' ') { builder.delete(builder.length() - 2, builder.length()); } builder.append(")"); return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.server; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * Result of a GCM multicast message request . */ public final class MulticastResult implements Serializable { private final int success; private final int failure; private final int canonicalIds; private final long multicastId; private final List<Result> results; private final List<Long> retryMulticastIds; public static final class Builder { private final List<Result> results = new ArrayList<Result>(); // required parameters private final int success; private final int failure; private final int canonicalIds; private final long multicastId; // optional parameters private List<Long> retryMulticastIds; public Builder(int success, int failure, int canonicalIds, long multicastId) { this.success = success; this.failure = failure; this.canonicalIds = canonicalIds; this.multicastId = multicastId; } public Builder addResult(Result result) { results.add(result); return this; } public Builder retryMulticastIds(List<Long> retryMulticastIds) { this.retryMulticastIds = retryMulticastIds; return this; } public MulticastResult build() { return new MulticastResult(this); } } private MulticastResult(Builder builder) { success = builder.success; failure = builder.failure; canonicalIds = builder.canonicalIds; multicastId = builder.multicastId; results = Collections.unmodifiableList(builder.results); List<Long> tmpList = builder.retryMulticastIds; if (tmpList == null) { tmpList = Collections.emptyList(); } retryMulticastIds = Collections.unmodifiableList(tmpList); } /** * Gets the multicast id. */ public long getMulticastId() { return multicastId; } /** * Gets the number of successful messages. */ public int getSuccess() { return success; } /** * Gets the total number of messages sent, regardless of the status. */ public int getTotal() { return success + failure; } /** * Gets the number of failed messages. */ public int getFailure() { return failure; } /** * Gets the number of successful messages that also returned a canonical * registration id. */ public int getCanonicalIds() { return canonicalIds; } /** * Gets the results of each individual message, which is immutable. */ public List<Result> getResults() { return results; } /** * Gets additional ids if more than one multicast message was sent. */ public List<Long> getRetryMulticastIds() { return retryMulticastIds; } @Override public String toString() { StringBuilder builder = new StringBuilder("MulticastResult(") .append("multicast_id=").append(multicastId).append(",") .append("total=").append(getTotal()).append(",") .append("success=").append(success).append(",") .append("failure=").append(failure).append(",") .append("canonical_ids=").append(canonicalIds).append(","); if (!results.isEmpty()) { builder.append("results: " + results); } return builder.toString(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE; import static com.google.android.gcm.GCMConstants.EXTRA_ERROR; import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID; import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE; import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED; import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE; import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK; import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES; import android.app.AlarmManager; import android.app.IntentService; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.os.SystemClock; import android.util.Log; import java.util.Random; import java.util.concurrent.TimeUnit; /** * Skeleton for application-specific {@link IntentService}s responsible for * handling communication from Google Cloud Messaging service. * <p> * The abstract methods in this class are called from its worker thread, and * hence should run in a limited amount of time. If they execute long * operations, they should spawn new threads, otherwise the worker thread will * be blocked. * <p> * Subclasses must provide a public no-arg constructor. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public abstract class GCMBaseIntentService extends IntentService { /** * Old TAG used for logging. Marked as deprecated since it should have * been private at first place. */ @Deprecated public static final String TAG = "GCMBaseIntentService"; private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService", "[" + getClass().getName() + "]: "); // wakelock private static final String WAKELOCK_KEY = "GCM_LIB"; private static PowerManager.WakeLock sWakeLock; // Java lock used to synchronize access to sWakelock private static final Object LOCK = GCMBaseIntentService.class; private final String[] mSenderIds; // instance counter private static int sCounter = 0; private static final Random sRandom = new Random(); private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS.toMillis(3600); // 1 hour /** * Constructor that does not set a sender id, useful when the sender id * is context-specific. * <p> * When using this constructor, the subclass <strong>must</strong> * override {@link #getSenderIds(Context)}, otherwise methods such as * {@link #onHandleIntent(Intent)} will throw an * {@link IllegalStateException} on runtime. */ protected GCMBaseIntentService() { this(getName("DynamicSenderIds"), null); } /** * Constructor used when the sender id(s) is fixed. */ protected GCMBaseIntentService(String... senderIds) { this(getName(senderIds), senderIds); } private GCMBaseIntentService(String name, String[] senderIds) { super(name); // name is used as base name for threads, etc. mSenderIds = senderIds; mLogger.log(Log.VERBOSE, "Intent service name: %s", name); } private static String getName(String senderId) { String name = "GCMIntentService-" + senderId + "-" + (++sCounter); return name; } private static String getName(String[] senderIds) { String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds); return getName(flatSenderIds); } /** * Gets the sender ids. * * <p>By default, it returns the sender ids passed in the constructor, but * it could be overridden to provide a dynamic sender id. * * @throws IllegalStateException if sender id was not set on constructor. */ protected String[] getSenderIds(Context context) { if (mSenderIds == null) { throw new IllegalStateException("sender id not set on constructor"); } return mSenderIds; } /** * Called when a cloud message has been received. * * @param context application's context. * @param intent intent containing the message payload as extras. */ protected abstract void onMessage(Context context, Intent intent); /** * Called when the GCM server tells pending messages have been deleted * because the device was idle. * * @param context application's context. * @param total total number of collapsed messages */ protected void onDeletedMessages(Context context, int total) { } /** * Called on a registration error that could be retried. * * <p>By default, it does nothing and returns {@literal true}, but could be * overridden to change that behavior and/or display the error. * * @param context application's context. * @param errorId error id returned by the GCM service. * * @return if {@literal true}, failed operation will be retried (using * exponential backoff). */ protected boolean onRecoverableError(Context context, String errorId) { return true; } /** * Called on registration or unregistration error. * * @param context application's context. * @param errorId error id returned by the GCM service. */ protected abstract void onError(Context context, String errorId); /** * Called after a device has been registered. * * @param context application's context. * @param registrationId the registration id returned by the GCM service. */ protected abstract void onRegistered(Context context, String registrationId); /** * Called after a device has been unregistered. * * @param registrationId the registration id that was previously registered. * @param context application's context. */ protected abstract void onUnregistered(Context context, String registrationId); @Override public final void onHandleIntent(Intent intent) { try { Context context = getApplicationContext(); String action = intent.getAction(); if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) { GCMRegistrar.setRetryBroadcastReceiver(context); handleRegistration(context, intent); } else if (action.equals(INTENT_FROM_GCM_MESSAGE)) { // checks for special messages String messageType = intent.getStringExtra(EXTRA_SPECIAL_MESSAGE); if (messageType != null) { if (messageType.equals(VALUE_DELETED_MESSAGES)) { String sTotal = intent.getStringExtra(EXTRA_TOTAL_DELETED); if (sTotal != null) { try { int total = Integer.parseInt(sTotal); mLogger.log(Log.VERBOSE, "Received notification for %d deleted" + "messages", total); onDeletedMessages(context, total); } catch (NumberFormatException e) { mLogger.log(Log.ERROR, "GCM returned invalid " + "number of deleted messages (%d)", sTotal); } } } else { // application is not using the latest GCM library mLogger.log(Log.ERROR, "Received unknown special message: %s", messageType); } } else { onMessage(context, intent); } } else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) { String packageOnIntent = intent.getPackage(); if (packageOnIntent == null || !packageOnIntent.equals( getApplicationContext().getPackageName())) { mLogger.log(Log.ERROR, "Ignoring retry intent from another package (%s)", packageOnIntent); return; } // retry last call if (GCMRegistrar.isRegistered(context)) { GCMRegistrar.internalUnregister(context); } else { String[] senderIds = getSenderIds(context); GCMRegistrar.internalRegister(context, senderIds); } } } finally { // Release the power lock, so phone can get back to sleep. // The lock is reference-counted by default, so multiple // messages are ok. // If onMessage() needs to spawn a thread or do something else, // it should use its own lock. synchronized (LOCK) { // sanity check for null as this is a public method if (sWakeLock != null) { sWakeLock.release(); } else { // should never happen during normal workflow mLogger.log(Log.ERROR, "Wakelock reference is null"); } } } } /** * Called from the broadcast receiver. * <p> * Will process the received intent, call handleMessage(), registered(), * etc. in background threads, with a wake lock, while keeping the service * alive. */ static void runIntentInService(Context context, Intent intent, String className) { synchronized (LOCK) { if (sWakeLock == null) { // This is called from BroadcastReceiver, there is no init. PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY); } } sWakeLock.acquire(); intent.setClassName(context, className); context.startService(intent); } private void handleRegistration(final Context context, Intent intent) { GCMRegistrar.cancelAppPendingIntent(); String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID); String error = intent.getStringExtra(EXTRA_ERROR); String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED); mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, " + "error = %s, unregistered = %s", registrationId, error, unregistered); // registration succeeded if (registrationId != null) { GCMRegistrar.resetBackoff(context); GCMRegistrar.setRegistrationId(context, registrationId); onRegistered(context, registrationId); return; } // unregistration succeeded if (unregistered != null) { // Remember we are unregistered GCMRegistrar.resetBackoff(context); String oldRegistrationId = GCMRegistrar.clearRegistrationId(context); onUnregistered(context, oldRegistrationId); return; } // last operation (registration or unregistration) returned an error; // Registration failed if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) { boolean retry = onRecoverableError(context, error); if (retry) { int backoffTimeMs = GCMRegistrar.getBackoff(context); int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs); mLogger.log(Log.DEBUG, "Scheduling registration retry, backoff = %d (%d)", nextAttempt, backoffTimeMs); Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY); retryIntent.setPackage(context.getPackageName()); PendingIntent retryPendingIntent = PendingIntent .getBroadcast(context, 0, retryIntent, 0); AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt, retryPendingIntent); // Next retry should wait longer. if (backoffTimeMs < MAX_BACKOFF_MS) { GCMRegistrar.setBackoff(context, backoffTimeMs * 2); } } else { mLogger.log(Log.VERBOSE, "Not retrying failed operation"); } } else { // Unrecoverable error, notify app onError(context, error); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.os.Build; import android.util.Log; import java.sql.Timestamp; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Utilities for device registration. * <p> * <strong>Note:</strong> this class uses a private {@link SharedPreferences} * object to keep track of the registration token. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMRegistrar { /** * Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)} * flag until it is considered expired. */ // NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8 public static final long DEFAULT_ON_SERVER_LIFESPAN_MS = 1000 * 3600 * 24 * 7; private static final String TAG = "GCMRegistrar"; private static final String BACKOFF_MS = "backoff_ms"; private static final String GSF_PACKAGE = "com.google.android.gsf"; private static final String PREFERENCES = "com.google.android.gcm"; private static final int DEFAULT_BACKOFF_MS = 3000; private static final String PROPERTY_REG_ID = "regId"; private static final String PROPERTY_APP_VERSION = "appVersion"; private static final String PROPERTY_ON_SERVER = "onServer"; private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME = "onServerExpirationTime"; private static final String PROPERTY_ON_SERVER_LIFESPAN = "onServerLifeSpan"; /** * {@link GCMBroadcastReceiver} instance used to handle the retry intent. * * <p> * This instance cannot be the same as the one defined in the manifest * because it needs a different permission. */ // guarded by GCMRegistrar.class private static GCMBroadcastReceiver sRetryReceiver; // guarded by GCMRegistrar.class private static Context sRetryReceiverContext; // guarded by GCMRegistrar.class private static String sRetryReceiverClassName; // guarded by GCMRegistrar.class private static PendingIntent sAppPendingIntent; /** * Checks if the device has the proper dependencies installed. * <p> * This method should be called when the application starts to verify that * the device supports GCM. * * @param context application context. * @throws UnsupportedOperationException if the device does not support GCM. */ public static void checkDevice(Context context) { int version = Build.VERSION.SDK_INT; if (version < 8) { throw new UnsupportedOperationException("Device must be at least " + "API Level 8 (instead of " + version + ")"); } PackageManager packageManager = context.getPackageManager(); try { packageManager.getPackageInfo(GSF_PACKAGE, 0); } catch (NameNotFoundException e) { throw new UnsupportedOperationException( "Device does not have package " + GSF_PACKAGE); } } /** * Checks that the application manifest is properly configured. * <p> * A proper configuration means: * <ol> * <li>It creates a custom permission called * {@code PACKAGE_NAME.permission.C2D_MESSAGE}. * <li>It defines at least one {@link BroadcastReceiver} with category * {@code PACKAGE_NAME}. * <li>The {@link BroadcastReceiver}(s) uses the * {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS} * permission. * <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents * ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * and * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}). * </ol> * ...where {@code PACKAGE_NAME} is the application package. * <p> * This method should be used during development time to verify that the * manifest is properly set up, but it doesn't need to be called once the * application is deployed to the users' devices. * * @param context application context. * @throws IllegalStateException if any of the conditions above is not met. */ public static void checkManifest(Context context) { PackageManager packageManager = context.getPackageManager(); String packageName = context.getPackageName(); String permissionName = packageName + ".permission.C2D_MESSAGE"; // check permission try { packageManager.getPermissionInfo(permissionName, PackageManager.GET_PERMISSIONS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Application does not define permission " + permissionName); } // check receivers PackageInfo receiversInfo; try { receiversInfo = packageManager.getPackageInfo( packageName, PackageManager.GET_RECEIVERS); } catch (NameNotFoundException e) { throw new IllegalStateException( "Could not get receivers for package " + packageName); } ActivityInfo[] receivers = receiversInfo.receivers; if (receivers == null || receivers.length == 0) { throw new IllegalStateException("No receiver for package " + packageName); } log(context, Log.VERBOSE, "number of receivers for %s: %d", packageName, receivers.length); Set<String> allowedReceivers = new HashSet<String>(); for (ActivityInfo receiver : receivers) { if (GCMConstants.PERMISSION_GCM_INTENTS.equals( receiver.permission)) { allowedReceivers.add(receiver.name); } } if (allowedReceivers.isEmpty()) { throw new IllegalStateException("No receiver allowed to receive " + GCMConstants.PERMISSION_GCM_INTENTS); } checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK); checkReceiver(context, allowedReceivers, GCMConstants.INTENT_FROM_GCM_MESSAGE); } private static void checkReceiver(Context context, Set<String> allowedReceivers, String action) { PackageManager pm = context.getPackageManager(); String packageName = context.getPackageName(); Intent intent = new Intent(action); intent.setPackage(packageName); List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent, PackageManager.GET_INTENT_FILTERS); if (receivers.isEmpty()) { throw new IllegalStateException("No receivers for action " + action); } log(context, Log.VERBOSE, "Found %d receivers for action %s", receivers.size(), action); // make sure receivers match for (ResolveInfo receiver : receivers) { String name = receiver.activityInfo.name; if (!allowedReceivers.contains(name)) { throw new IllegalStateException("Receiver " + name + " is not set with permission " + GCMConstants.PERMISSION_GCM_INTENTS); } } } /** * Initiate messaging registration for the current application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with * either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or * {@link GCMConstants#EXTRA_ERROR}. * * @param context application context. * @param senderIds Google Project ID of the accounts authorized to send * messages to this application. * @throws IllegalStateException if device does not have all GCM * dependencies installed. */ public static void register(Context context, String... senderIds) { GCMRegistrar.resetBackoff(context); internalRegister(context, senderIds); } static void internalRegister(Context context, String... senderIds) { String flatSenderIds = getFlatSenderIds(senderIds); log(context, Log.VERBOSE, "Registering app for senders %s", flatSenderIds); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds); context.startService(intent); } /** * Unregister the application. * <p> * The result will be returned as an * {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an * {@link GCMConstants#EXTRA_UNREGISTERED} extra. */ public static void unregister(Context context) { GCMRegistrar.resetBackoff(context); internalUnregister(context); } static void internalUnregister(Context context) { log(context, Log.VERBOSE, "Unregistering app"); Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION); intent.setPackage(GSF_PACKAGE); setPackageNameExtra(context, intent); context.startService(intent); } static String getFlatSenderIds(String... senderIds) { if (senderIds == null || senderIds.length == 0) { throw new IllegalArgumentException("No senderIds"); } StringBuilder builder = new StringBuilder(senderIds[0]); for (int i = 1; i < senderIds.length; i++) { builder.append(',').append(senderIds[i]); } return builder.toString(); } /** * Clear internal resources. * * <p> * This method should be called by the main activity's {@code onDestroy()} * method. */ public static synchronized void onDestroy(Context context) { if (sRetryReceiver != null) { log(context, Log.VERBOSE, "Unregistering retry receiver"); sRetryReceiverContext.unregisterReceiver(sRetryReceiver); sRetryReceiver = null; sRetryReceiverContext = null; } } static synchronized void cancelAppPendingIntent() { if (sAppPendingIntent != null) { sAppPendingIntent.cancel(); sAppPendingIntent = null; } } private synchronized static void setPackageNameExtra(Context context, Intent intent) { if (sAppPendingIntent == null) { log(context, Log.VERBOSE, "Creating pending intent to get package name"); sAppPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(), 0); } intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT, sAppPendingIntent); } /** * Lazy initializes the {@link GCMBroadcastReceiver} instance. */ static synchronized void setRetryBroadcastReceiver(Context context) { if (sRetryReceiver == null) { if (sRetryReceiverClassName == null) { // should never happen log(context, Log.ERROR, "internal error: retry receiver class not set yet"); sRetryReceiver = new GCMBroadcastReceiver(); } else { Class<?> clazz; try { clazz = Class.forName(sRetryReceiverClassName); sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance(); } catch (Exception e) { log(context, Log.ERROR, "Could not create instance of %s. " + "Using %s directly.", sRetryReceiverClassName, GCMBroadcastReceiver.class.getName()); sRetryReceiver = new GCMBroadcastReceiver(); } } String category = context.getPackageName(); IntentFilter filter = new IntentFilter( GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY); filter.addCategory(category); log(context, Log.VERBOSE, "Registering retry receiver"); sRetryReceiverContext = context; sRetryReceiverContext.registerReceiver(sRetryReceiver, filter); } } /** * Sets the name of the retry receiver class. */ static synchronized void setRetryReceiverClassName(Context context, String className) { log(context, Log.VERBOSE, "Setting the name of retry receiver class to %s", className); sRetryReceiverClassName = className; } /** * Gets the current registration id for application on GCM service. * <p> * If result is empty, the registration has failed. * * @return registration id, or empty string if the registration is not * complete. */ public static String getRegistrationId(Context context) { final SharedPreferences prefs = getGCMPreferences(context); String registrationId = prefs.getString(PROPERTY_REG_ID, ""); // check if app was updated; if so, it must clear registration id to // avoid a race condition if GCM sends a message int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE); int newVersion = getAppVersion(context); if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) { log(context, Log.VERBOSE, "App version changed from %d to %d;" + "resetting registration id", oldVersion, newVersion); clearRegistrationId(context); registrationId = ""; } return registrationId; } /** * Checks whether the application was successfully registered on GCM * service. */ public static boolean isRegistered(Context context) { return getRegistrationId(context).length() > 0; } /** * Clears the registration id in the persistence store. * * <p>As a side-effect, it also expires the registeredOnServer property. * * @param context application's context. * @return old registration id. */ static String clearRegistrationId(Context context) { setRegisteredOnServer(context, null, 0); return setRegistrationId(context, ""); } /** * Sets the registration id in the persistence store. * * @param context application's context. * @param regId registration id */ static String setRegistrationId(Context context, String regId) { final SharedPreferences prefs = getGCMPreferences(context); String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, ""); int appVersion = getAppVersion(context); log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion); Editor editor = prefs.edit(); editor.putString(PROPERTY_REG_ID, regId); editor.putInt(PROPERTY_APP_VERSION, appVersion); editor.commit(); return oldRegistrationId; } /** * Sets whether the device was successfully registered in the server side. */ public static void setRegisteredOnServer(Context context, boolean flag) { // set the flag's expiration date long lifespan = getRegisterOnServerLifespan(context); long expirationTime = System.currentTimeMillis() + lifespan; setRegisteredOnServer(context, flag, expirationTime); } private static void setRegisteredOnServer(Context context, Boolean flag, long expirationTime) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); if (flag != null) { editor.putBoolean(PROPERTY_ON_SERVER, flag); log(context, Log.VERBOSE, "Setting registeredOnServer flag as %b until %s", flag, new Timestamp(expirationTime)); } else { log(context, Log.VERBOSE, "Setting registeredOnServer expiration to %s", new Timestamp(expirationTime)); } editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime); editor.commit(); } /** * Checks whether the device was successfully registered in the server side, * as set by {@link #setRegisteredOnServer(Context, boolean)}. * * <p>To avoid the scenario where the device sends the registration to the * server but the server loses it, this flag has an expiration date, which * is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed * by {@link #setRegisterOnServerLifespan(Context, long)}). */ public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { log(context, Log.VERBOSE, "flag expired on: %s", new Timestamp(expirationTime)); return false; } } return isRegistered; } /** * Gets how long (in milliseconds) the {@link #isRegistered(Context)} * property is valid. * * @return value set by {@link #setRegisteredOnServer(Context, boolean)} or * {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set. */ public static long getRegisterOnServerLifespan(Context context) { final SharedPreferences prefs = getGCMPreferences(context); long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN, DEFAULT_ON_SERVER_LIFESPAN_MS); return lifespan; } /** * Sets how long (in milliseconds) the {@link #isRegistered(Context)} * flag is valid. */ public static void setRegisterOnServerLifespan(Context context, long lifespan) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan); editor.commit(); } /** * Gets the application version. */ private static int getAppVersion(Context context) { try { PackageInfo packageInfo = context.getPackageManager() .getPackageInfo(context.getPackageName(), 0); return packageInfo.versionCode; } catch (NameNotFoundException e) { // should never happen throw new RuntimeException("Coult not get package name: " + e); } } /** * Resets the backoff counter. * <p> * This method should be called after a GCM call succeeds. * * @param context application's context. */ static void resetBackoff(Context context) { log(context, Log.VERBOSE, "Resetting backoff"); setBackoff(context, DEFAULT_BACKOFF_MS); } /** * Gets the current backoff counter. * * @param context application's context. * @return current backoff counter, in milliseconds. */ static int getBackoff(Context context) { final SharedPreferences prefs = getGCMPreferences(context); return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS); } /** * Sets the backoff counter. * <p> * This method should be called after a GCM call fails, passing an * exponential value. * * @param context application's context. * @param backoff new backoff counter, in milliseconds. */ static void setBackoff(Context context, int backoff) { final SharedPreferences prefs = getGCMPreferences(context); Editor editor = prefs.edit(); editor.putInt(BACKOFF_MS, backoff); editor.commit(); } private static SharedPreferences getGCMPreferences(Context context) { return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE); } /** * Logs a message on logcat. * * @param context application's context. * @param priority logging priority * @param template message's template * @param args list of arguments */ private static void log(Context context, int priority, String template, Object... args) { if (Log.isLoggable(TAG, priority)) { String message = String.format(template, args); Log.println(priority, TAG, "[" + context.getPackageName() + "]: " + message); } } private GCMRegistrar() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; /** * Constants used by the GCM library. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public final class GCMConstants { /** * Intent sent to GCM to register the application. */ public static final String INTENT_TO_GCM_REGISTRATION = "com.google.android.c2dm.intent.REGISTER"; /** * Intent sent to GCM to unregister the application. */ public static final String INTENT_TO_GCM_UNREGISTRATION = "com.google.android.c2dm.intent.UNREGISTER"; /** * Intent sent by GCM indicating with the result of a registration request. */ public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK = "com.google.android.c2dm.intent.REGISTRATION"; /** * Intent used by the GCM library to indicate that the registration call * should be retried. */ public static final String INTENT_FROM_GCM_LIBRARY_RETRY = "com.google.android.gcm.intent.RETRY"; /** * Intent sent by GCM containing a message. */ public static final String INTENT_FROM_GCM_MESSAGE = "com.google.android.c2dm.intent.RECEIVE"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to indicate which senders (Google API project ids) can send messages to * the application. */ public static final String EXTRA_SENDER = "sender"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION} * to get the application info. */ public static final String EXTRA_APPLICATION_PENDING_INTENT = "app"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate that the application has been unregistered. */ public static final String EXTRA_UNREGISTERED = "unregistered"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate an error when the registration fails. * See constants starting with ERROR_ for possible values. */ public static final String EXTRA_ERROR = "error"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} * to indicate the registration id when the registration succeeds. */ public static final String EXTRA_REGISTRATION_ID = "registration_id"; /** * Type of message present in the * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * intent. * This extra is only set for special messages sent from GCM, not for * messages originated from the application. */ public static final String EXTRA_SPECIAL_MESSAGE = "message_type"; /** * Special message indicating the server deleted the pending messages. */ public static final String VALUE_DELETED_MESSAGES = "deleted_messages"; /** * Number of messages deleted by the server because the device was idle. * Present only on messages of special type * {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES} */ public static final String EXTRA_TOTAL_DELETED = "total_deleted"; /** * Extra used on * {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE} * to indicate which sender (Google API project id) sent the message. */ public static final String EXTRA_FROM = "from"; /** * Permission necessary to receive GCM intents. */ public static final String PERMISSION_GCM_INTENTS = "com.google.android.c2dm.permission.SEND"; /** * @see GCMBroadcastReceiver */ public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME = ".GCMIntentService"; /** * The device can't read the response, or there was a 500/503 from the * server that can be retried later. The application should use exponential * back off and retry. */ public static final String ERROR_SERVICE_NOT_AVAILABLE = "SERVICE_NOT_AVAILABLE"; /** * There is no Google account on the phone. The application should ask the * user to open the account manager and add a Google account. */ public static final String ERROR_ACCOUNT_MISSING = "ACCOUNT_MISSING"; /** * Bad password. The application should ask the user to enter his/her * password, and let user retry manually later. Fix on the device side. */ public static final String ERROR_AUTHENTICATION_FAILED = "AUTHENTICATION_FAILED"; /** * The request sent by the phone does not contain the expected parameters. * This phone doesn't currently support GCM. */ public static final String ERROR_INVALID_PARAMETERS = "INVALID_PARAMETERS"; /** * The sender account is not recognized. Fix on the device side. */ public static final String ERROR_INVALID_SENDER = "INVALID_SENDER"; /** * Incorrect phone registration with Google. This phone doesn't currently * support GCM. */ public static final String ERROR_PHONE_REGISTRATION_ERROR = "PHONE_REGISTRATION_ERROR"; private GCMConstants() { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import android.util.Log; /** * Custom logger. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated class GCMLogger { private final String mTag; // can't use class name on TAG since size is limited to 23 chars private final String mLogPrefix; GCMLogger(String tag, String logPrefix) { mTag = tag; mLogPrefix = logPrefix; } /** * Logs a message on logcat. * * @param priority logging priority * @param template message's template * @param args list of arguments */ protected void log(int priority, String template, Object... args) { if (Log.isLoggable(mTag, priority)) { String message = String.format(template, args); Log.println(priority, mTag, mLogPrefix + message); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm; import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * {@link BroadcastReceiver} that receives GCM messages and delivers them to * an application-specific {@link GCMBaseIntentService} subclass. * <p> * By default, the {@link GCMBaseIntentService} class belongs to the application * main package and is named * {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class, * the {@link #getGCMIntentServiceClassName(Context)} must be overridden. * * @deprecated GCM library has been moved to Google Play Services * (com.google.android.gms.gcm), and this version is no longer supported. */ @Deprecated public class GCMBroadcastReceiver extends BroadcastReceiver { private static boolean mReceiverSet = false; private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver", "[" + getClass().getName() + "]: "); @Override public final void onReceive(Context context, Intent intent) { mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction()); // do a one-time check if app is using a custom GCMBroadcastReceiver if (!mReceiverSet) { mReceiverSet = true; GCMRegistrar.setRetryReceiverClassName(context, getClass().getName()); } String className = getGCMIntentServiceClassName(context); mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className); // Delegates to the application-specific intent service. GCMBaseIntentService.runIntentInService(context, intent, className); setResult(Activity.RESULT_OK, null /* data */, null /* extra */); } /** * Gets the class name of the intent service that will handle GCM messages. */ protected String getGCMIntentServiceClassName(Context context) { return getDefaultIntentServiceClassName(context); } /** * Gets the default class name of the intent service that will handle GCM * messages. */ static final String getDefaultIntentServiceClassName(Context context) { String className = context.getPackageName() + DEFAULT_INTENT_SERVICE_CLASS_NAME; return className; } }
Java
/** Automatically generated file. DO NOT MODIFY */ package com.google.android.gcm; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { private static final int MULTICAST_SIZE = 1000; private Sender sender; private static final Executor threadPool = Executors.newFixedThreadPool(5); @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String registrationId = devices.get(0); Message message = new Message.Builder().build(); Result result = sender.send(message, registrationId, 5); status = "Sent message to one device: " + result; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == MULTICAST_SIZE || counter == total) { asyncSend(partialDevices); partialDevices.clear(); tasks++; } } status = "Asynchronously sending " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } private void asyncSend(List<String> partialDevices) { // make a copy final List<String> devices = new ArrayList<String>(partialDevices); threadPool.execute(new Runnable() { public void run() { Message message = new Message.Builder().build(); MulticastResult multicastResult; try { multicastResult = sender.send(message, devices, 5); } catch (IOException e) { logger.log(Level.SEVERE, "Error posting messages", e); return; } List<Result> results = multicastResult.getResults(); // analyze the results for (int i = 0; i < devices.size(); i++) { String regId = devices.get(i); Result result = results.get(i); String messageId = result.getMessageId(); if (messageId != null) { logger.fine("Succesfully sent message to device: " + regId + "; messageId = " + messageId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.info("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it logger.info("Unregistered device: " + regId); Datastore.unregister(regId); } else { logger.severe("Error sending message to " + regId + ": " + error); } } } }}); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is thread-safe but not persistent (it will lost the data when the * app is restarted) - it is meant just as an example. */ public final class Datastore { private static final List<String> regIds = new ArrayList<String>(); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. */ public static void register(String regId) { logger.info("Registering " + regId); synchronized (regIds) { regIds.add(regId); } } /** * Unregisters a device. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); synchronized (regIds) { regIds.remove(regId); } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); synchronized (regIds) { regIds.remove(oldId); regIds.add(newId); } } /** * Gets all registered devices. */ public static List<String> getDevices() { synchronized (regIds) { return new ArrayList<String>(regIds); } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from a * {@value #PATH} file located in the classpath (typically under * {@code WEB-INF/classes}). */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String PATH = "/api.key"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { logger.info("Reading " + PATH + " from resources (probably from " + "WEB-INF/classes"); String key = getKey(); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key); } /** * Gets the access key. */ protected String getKey() { InputStream stream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(PATH); if (stream == null) { throw new IllegalStateException("Could not find file " + PATH + " on web resources)"); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); try { String key = reader.readLine(); return key; } catch (IOException e) { throw new RuntimeException("Could not read file " + PATH, e); } finally { try { reader.close(); } catch (IOException e) { logger.log(Level.WARNING, "Exception closing " + PATH, e); } } } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } List<String> devices = Datastore.getDevices(); if (devices.isEmpty()) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + devices.size() + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION; import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import com.google.android.gcm.GCMRegistrar; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; /** * Main UI for the demo app. */ public class DemoActivity extends Activity { TextView mDisplay; AsyncTask<Void, Void, Void> mRegisterTask; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); checkNotNull(SERVER_URL, "SERVER_URL"); checkNotNull(SENDER_ID, "SENDER_ID"); // Make sure the device has the proper dependencies. GCMRegistrar.checkDevice(this); // Make sure the manifest was properly set - comment out this line // while developing the app, then uncomment it when it's ready. GCMRegistrar.checkManifest(this); setContentView(R.layout.main); mDisplay = (TextView) findViewById(R.id.display); registerReceiver(mHandleMessageReceiver, new IntentFilter(DISPLAY_MESSAGE_ACTION)); final String regId = GCMRegistrar.getRegistrationId(this); if (regId.equals("")) { // Automatically registers application on startup. GCMRegistrar.register(this, SENDER_ID); } else { // Device is already registered on GCM, check server. if (GCMRegistrar.isRegisteredOnServer(this)) { // Skips registration. mDisplay.append(getString(R.string.already_registered) + "\n"); } else { // Try to register again, but not in the UI thread. // It's also necessary to cancel the thread onDestroy(), // hence the use of AsyncTask instead of a raw thread. final Context context = this; mRegisterTask = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { ServerUtilities.register(context, regId); return null; } @Override protected void onPostExecute(Void result) { mRegisterTask = null; } }; mRegisterTask.execute(null, null, null); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { /* * Typically, an application registers automatically, so options * below are disabled. Uncomment them if you want to manually * register or unregister the device (you will also need to * uncomment the equivalent options on options_menu.xml). */ /* case R.id.options_register: GCMRegistrar.register(this, SENDER_ID); return true; case R.id.options_unregister: GCMRegistrar.unregister(this); return true; */ case R.id.options_clear: mDisplay.setText(null); return true; case R.id.options_exit: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onDestroy() { if (mRegisterTask != null) { mRegisterTask.cancel(true); } unregisterReceiver(mHandleMessageReceiver); GCMRegistrar.onDestroy(this); super.onDestroy(); } private void checkNotNull(Object reference, String name) { if (reference == null) { throw new NullPointerException( getString(R.string.error_config, name)); } } private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); mDisplay.append(newMessage + "\n"); } }; }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL; import static com.google.android.gcm.demo.app.CommonUtilities.TAG; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import com.google.android.gcm.GCMRegistrar; import android.content.Context; import android.util.Log; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Random; /** * Helper class used to communicate with the demo server. */ public final class ServerUtilities { private static final int MAX_ATTEMPTS = 5; private static final int BACKOFF_MILLI_SECONDS = 2000; private static final Random random = new Random(); /** * Register this account/device pair within the server. * */ static void register(final Context context, final String regId) { Log.i(TAG, "registering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/register"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000); // Once GCM returns a registration id, we need to register it in the // demo server. As the server might be down, we will retry it a couple // times. for (int i = 1; i <= MAX_ATTEMPTS; i++) { Log.d(TAG, "Attempt #" + i + " to register"); try { displayMessage(context, context.getString( R.string.server_registering, i, MAX_ATTEMPTS)); post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, true); String message = context.getString(R.string.server_registered); CommonUtilities.displayMessage(context, message); return; } catch (IOException e) { // Here we are simplifying and retrying on any error; in a real // application, it should retry only on unrecoverable errors // (like HTTP error code 503). Log.e(TAG, "Failed to register on attempt " + i + ":" + e); if (i == MAX_ATTEMPTS) { break; } try { Log.d(TAG, "Sleeping for " + backoff + " ms before retry"); Thread.sleep(backoff); } catch (InterruptedException e1) { // Activity finished before we complete - exit. Log.d(TAG, "Thread interrupted: abort remaining retries!"); Thread.currentThread().interrupt(); return; } // increase backoff exponentially backoff *= 2; } } String message = context.getString(R.string.server_register_error, MAX_ATTEMPTS); CommonUtilities.displayMessage(context, message); } /** * Unregister this account/device pair within the server. */ static void unregister(final Context context, final String regId) { Log.i(TAG, "unregistering device (regId = " + regId + ")"); String serverUrl = SERVER_URL + "/unregister"; Map<String, String> params = new HashMap<String, String>(); params.put("regId", regId); try { post(serverUrl, params); GCMRegistrar.setRegisteredOnServer(context, false); String message = context.getString(R.string.server_unregistered); CommonUtilities.displayMessage(context, message); } catch (IOException e) { // At this point the device is unregistered from GCM, but still // registered in the server. // We could try to unregister again, but it is not necessary: // if the server tries to send a message to the device, it will get // a "NotRegistered" error message and should unregister the device. String message = context.getString(R.string.server_unregister_error, e.getMessage()); CommonUtilities.displayMessage(context, message); } } /** * Issue a POST request to the server. * * @param endpoint POST address. * @param params request parameters. * * @throws IOException propagated from POST. */ private static void post(String endpoint, Map<String, String> params) throws IOException { URL url; try { url = new URL(endpoint); } catch (MalformedURLException e) { throw new IllegalArgumentException("invalid url: " + endpoint); } StringBuilder bodyBuilder = new StringBuilder(); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); // constructs the POST body using the parameters while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); bodyBuilder.append(param.getKey()).append('=') .append(param.getValue()); if (iterator.hasNext()) { bodyBuilder.append('&'); } } String body = bodyBuilder.toString(); Log.v(TAG, "Posting '" + body + "' to " + url); byte[] bytes = body.getBytes(); HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setUseCaches(false); conn.setFixedLengthStreamingMode(bytes.length); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"); // post the request OutputStream out = conn.getOutputStream(); out.write(bytes); out.close(); // handle the response int status = conn.getResponseCode(); if (status != 200) { throw new IOException("Post failed with error code " + status); } } finally { if (conn != null) { conn.disconnect(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import android.content.Context; import android.content.Intent; /** * Helper class providing methods and constants common to other classes in the * app. */ public final class CommonUtilities { /** * Base URL of the Demo Server (such as http://my_host:8080/gcm-demo) */ static final String SERVER_URL = null; /** * Google API project id registered to use GCM. */ static final String SENDER_ID = null; /** * Tag used on log messages. */ static final String TAG = "GCMDemo"; /** * Intent used to display a message in the screen. */ static final String DISPLAY_MESSAGE_ACTION = "com.google.android.gcm.demo.app.DISPLAY_MESSAGE"; /** * Intent's extra that contains the message to be displayed. */ static final String EXTRA_MESSAGE = "message"; /** * Notifies UI to display a message. * <p> * This method is defined in the common helper because it's used both by * the UI and the background service. * * @param context application's context. * @param message message to be displayed. */ static void displayMessage(Context context, String message) { Intent intent = new Intent(DISPLAY_MESSAGE_ACTION); intent.putExtra(EXTRA_MESSAGE, message); context.sendBroadcast(intent); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.app; import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID; import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.android.gcm.GCMBaseIntentService; /** * IntentService responsible for handling GCM messages. */ public class GCMIntentService extends GCMBaseIntentService { @SuppressWarnings("hiding") private static final String TAG = "GCMIntentService"; public GCMIntentService() { super(SENDER_ID); } @Override protected void onRegistered(Context context, String registrationId) { Log.i(TAG, "Device registered: regId = " + registrationId); displayMessage(context, getString(R.string.gcm_registered, registrationId)); ServerUtilities.register(context, registrationId); } @Override protected void onUnregistered(Context context, String registrationId) { Log.i(TAG, "Device unregistered"); displayMessage(context, getString(R.string.gcm_unregistered)); ServerUtilities.unregister(context, registrationId); } @Override protected void onMessage(Context context, Intent intent) { Log.i(TAG, "Received message. Extras: " + intent.getExtras()); String message = getString(R.string.gcm_message); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override protected void onDeletedMessages(Context context, int total) { Log.i(TAG, "Received deleted messages notification"); String message = getString(R.string.gcm_deleted, total); displayMessage(context, message); // notifies user generateNotification(context, message); } @Override public void onError(Context context, String errorId) { Log.i(TAG, "Received error: " + errorId); displayMessage(context, getString(R.string.gcm_error, errorId)); } @Override protected boolean onRecoverableError(Context context, String errorId) { // log message Log.i(TAG, "Received recoverable error: " + errorId); displayMessage(context, getString(R.string.gcm_recoverable_error, errorId)); return super.onRecoverableError(context, errorId); } /** * Issues a notification to inform the user that server has sent a message. */ private static void generateNotification(Context context, String message) { int icon = R.drawable.ic_stat_gcm; long when = System.currentTimeMillis(); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(icon, message, when); String title = context.getString(R.string.app_name); Intent notificationIntent = new Intent(context, DemoActivity.class); // set intent so it does not start a new activity notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notification.setLatestEventInfo(context, title, message, intent); notification.flags |= Notification.FLAG_AUTO_CANCEL; notificationManager.notify(0, notification); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds a new message to all registered devices. * <p> * This servlet is used just by the browser (i.e., not device). */ @SuppressWarnings("serial") public class SendAllMessagesServlet extends BaseServlet { /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { List<String> devices = Datastore.getDevices(); String status; if (devices.isEmpty()) { status = "Message ignored as there is no device registered!"; } else { Queue queue = QueueFactory.getQueue("gcm"); // NOTE: check below is for demonstration purposes; a real application // could always send a multicast, even for just one recipient if (devices.size() == 1) { // send a single message using plain post String device = devices.get(0); queue.add(withUrl("/send").param( SendMessageServlet.PARAMETER_DEVICE, device)); status = "Single message queued for registration id " + device; } else { // send a multicast message using JSON // must split in chunks of 1000 devices (GCM limit) int total = devices.size(); List<String> partialDevices = new ArrayList<String>(total); int counter = 0; int tasks = 0; for (String device : devices) { counter++; partialDevices.add(device); int partialSize = partialDevices.size(); if (partialSize == Datastore.MULTICAST_SIZE || counter == total) { String multicastKey = Datastore.createMulticast(partialDevices); logger.fine("Queuing " + partialSize + " devices on multicast " + multicastKey); TaskOptions taskOptions = TaskOptions.Builder .withUrl("/send") .param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey) .method(Method.POST); queue.add(taskOptions); partialDevices.clear(); tasks++; } } status = "Queued tasks to send " + tasks + " multicast messages to " + total + " devices"; } } req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString()); getServletContext().getRequestDispatcher("/home").forward(req, resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.android.gcm.server.Constants; import com.google.android.gcm.server.Message; import com.google.android.gcm.server.MulticastResult; import com.google.android.gcm.server.Result; import com.google.android.gcm.server.Sender; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that sends a message to a device. * <p> * This servlet is invoked by AppEngine's Push Queue mechanism. */ @SuppressWarnings("serial") public class SendMessageServlet extends BaseServlet { private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount"; private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName"; private static final int MAX_RETRY = 3; static final String PARAMETER_DEVICE = "device"; static final String PARAMETER_MULTICAST = "multicastKey"; private Sender sender; @Override public void init(ServletConfig config) throws ServletException { super.init(config); sender = newSender(config); } /** * Creates the {@link Sender} based on the servlet settings. */ protected Sender newSender(ServletConfig config) { String key = (String) config.getServletContext() .getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY); return new Sender(key); } /** * Indicates to App Engine that this task should be retried. */ private void retryTask(HttpServletResponse resp) { resp.setStatus(500); } /** * Indicates to App Engine that this task is done. */ private void taskDone(HttpServletResponse resp) { resp.setStatus(200); } /** * Processes the request to add a new message. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (req.getHeader(HEADER_QUEUE_NAME) == null) { throw new IOException("Missing header " + HEADER_QUEUE_NAME); } String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT); logger.fine("retry count: " + retryCountHeader); if (retryCountHeader != null) { int retryCount = Integer.parseInt(retryCountHeader); if (retryCount > MAX_RETRY) { logger.severe("Too many retries, dropping task"); taskDone(resp); return; } } String regId = req.getParameter(PARAMETER_DEVICE); if (regId != null) { sendSingleMessage(regId, resp); return; } String multicastKey = req.getParameter(PARAMETER_MULTICAST); if (multicastKey != null) { sendMulticastMessage(multicastKey, resp); return; } logger.severe("Invalid request!"); taskDone(resp); return; } private Message createMessage() { Message message = new Message.Builder().build(); return message; } private void sendSingleMessage(String regId, HttpServletResponse resp) { logger.info("Sending message to device " + regId); Message message = createMessage(); Result result; try { result = sender.sendNoRetry(message, regId); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); taskDone(resp); return; } if (result == null) { retryTask(resp); return; } if (result.getMessageId() != null) { logger.info("Succesfully sent message to device " + regId); String canonicalRegId = result.getCanonicalRegistrationId(); if (canonicalRegId != null) { // same device has more than on registration id: update it logger.finest("canonicalRegId " + canonicalRegId); Datastore.updateRegistration(regId, canonicalRegId); } } else { String error = result.getErrorCodeName(); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } else { logger.severe("Error sending message to device " + regId + ": " + error); } } } private void sendMulticastMessage(String multicastKey, HttpServletResponse resp) { // Recover registration ids from datastore List<String> regIds = Datastore.getMulticast(multicastKey); Message message = createMessage(); MulticastResult multicastResult; try { multicastResult = sender.sendNoRetry(message, regIds); } catch (IOException e) { logger.log(Level.SEVERE, "Exception posting " + message, e); multicastDone(resp, multicastKey); return; } boolean allDone = true; // check if any registration id must be updated if (multicastResult.getCanonicalIds() != 0) { List<Result> results = multicastResult.getResults(); for (int i = 0; i < results.size(); i++) { String canonicalRegId = results.get(i).getCanonicalRegistrationId(); if (canonicalRegId != null) { String regId = regIds.get(i); Datastore.updateRegistration(regId, canonicalRegId); } } } if (multicastResult.getFailure() != 0) { // there were failures, check if any could be retried List<Result> results = multicastResult.getResults(); List<String> retriableRegIds = new ArrayList<String>(); for (int i = 0; i < results.size(); i++) { String error = results.get(i).getErrorCodeName(); if (error != null) { String regId = regIds.get(i); logger.warning("Got error (" + error + ") for regId " + regId); if (error.equals(Constants.ERROR_NOT_REGISTERED)) { // application has been removed from device - unregister it Datastore.unregister(regId); } if (error.equals(Constants.ERROR_UNAVAILABLE)) { retriableRegIds.add(regId); } } } if (!retriableRegIds.isEmpty()) { // update task Datastore.updateMulticast(multicastKey, retriableRegIds); allDone = false; retryTask(resp); } } if (allDone) { multicastDone(resp, multicastKey); } else { retryTask(resp); } } private void multicastDone(HttpServletResponse resp, String encodedKey) { Datastore.deleteMulticast(encodedKey); taskDone(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that unregisters a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION} with an * {@code unregistered} extra. */ @SuppressWarnings("serial") public class UnregisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.unregister(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that registers a device, whose registration id is identified by * {@link #PARAMETER_REG_ID}. * * <p> * The client app should call this servlet everytime it receives a * {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an * error or {@code unregistered} extra. */ @SuppressWarnings("serial") public class RegisterServlet extends BaseServlet { private static final String PARAMETER_REG_ID = "regId"; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String regId = getParameter(req, PARAMETER_REG_ID); Datastore.register(regId); setSuccess(resp); } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import com.google.appengine.api.datastore.Query.FilterOperator; import com.google.appengine.api.datastore.Transaction; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Logger; /** * Simple implementation of a data store using standard Java collections. * <p> * This class is neither persistent (it will lost the data when the app is * restarted) nor thread safe. */ public final class Datastore { static final int MULTICAST_SIZE = 1000; private static final String DEVICE_TYPE = "Device"; private static final String DEVICE_REG_ID_PROPERTY = "regId"; private static final String MULTICAST_TYPE = "Multicast"; private static final String MULTICAST_REG_IDS_PROPERTY = "regIds"; private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder .withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE); private static final Logger logger = Logger.getLogger(Datastore.class.getName()); private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); private Datastore() { throw new UnsupportedOperationException(); } /** * Registers a device. * * @param regId device's registration id. */ public static void register(String regId) { logger.info("Registering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity != null) { logger.fine(regId + " is already registered; ignoring."); return; } entity = new Entity(DEVICE_TYPE); entity.setProperty(DEVICE_REG_ID_PROPERTY, regId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Unregisters a device. * * @param regId device's registration id. */ public static void unregister(String regId) { logger.info("Unregistering " + regId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(regId); if (entity == null) { logger.warning("Device " + regId + " already unregistered"); } else { Key key = entity.getKey(); datastore.delete(key); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates the registration id of a device. */ public static void updateRegistration(String oldId, String newId) { logger.info("Updating " + oldId + " to " + newId); Transaction txn = datastore.beginTransaction(); try { Entity entity = findDeviceByRegId(oldId); if (entity == null) { logger.warning("No device for registration id " + oldId); return; } entity.setProperty(DEVICE_REG_ID_PROPERTY, newId); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Gets all registered devices. */ public static List<String> getDevices() { List<String> devices; Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE); Iterable<Entity> entities = datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS); devices = new ArrayList<String>(); for (Entity entity : entities) { String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY); devices.add(device); } txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return devices; } /** * Gets the number of total devices. */ public static int getTotalDevices() { Transaction txn = datastore.beginTransaction(); try { Query query = new Query(DEVICE_TYPE).setKeysOnly(); List<Entity> allKeys = datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS); int total = allKeys.size(); logger.fine("Total number of devices: " + total); txn.commit(); return total; } finally { if (txn.isActive()) { txn.rollback(); } } } private static Entity findDeviceByRegId(String regId) { Query query = new Query(DEVICE_TYPE) .addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId); PreparedQuery preparedQuery = datastore.prepare(query); List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS); Entity entity = null; if (!entities.isEmpty()) { entity = entities.get(0); } int size = entities.size(); if (size > 0) { logger.severe( "Found " + size + " entities for regId " + regId + ": " + entities); } return entity; } /** * Creates a persistent record with the devices to be notified using a * multicast message. * * @param devices registration ids of the devices. * @return encoded key for the persistent record. */ public static String createMulticast(List<String> devices) { logger.info("Storing multicast for " + devices.size() + " devices"); String encodedKey; Transaction txn = datastore.beginTransaction(); try { Entity entity = new Entity(MULTICAST_TYPE); entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); Key key = entity.getKey(); encodedKey = KeyFactory.keyToString(key); logger.fine("multicast key: " + encodedKey); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } return encodedKey; } /** * Gets a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static List<String> getMulticast(String encodedKey) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { entity = datastore.get(key); @SuppressWarnings("unchecked") List<String> devices = (List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY); txn.commit(); return devices; } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return Collections.emptyList(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Updates a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. * @param devices new list of registration ids of the devices. */ public static void updateMulticast(String encodedKey, List<String> devices) { Key key = KeyFactory.stringToKey(encodedKey); Entity entity; Transaction txn = datastore.beginTransaction(); try { try { entity = datastore.get(key); } catch (EntityNotFoundException e) { logger.severe("No entity for key " + key); return; } entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices); datastore.put(entity); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } /** * Deletes a persistent record with the devices to be notified using a * multicast message. * * @param encodedKey encoded key for the persistent record. */ public static void deleteMulticast(String encodedKey) { Transaction txn = datastore.beginTransaction(); try { Key key = KeyFactory.stringToKey(encodedKey); datastore.delete(key); txn.commit(); } finally { if (txn.isActive()) { txn.rollback(); } } } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.util.Enumeration; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Skeleton class for all servlets in this package. */ @SuppressWarnings("serial") abstract class BaseServlet extends HttpServlet { // change to true to allow GET calls static final boolean DEBUG = true; protected final Logger logger = Logger.getLogger(getClass().getName()); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { if (DEBUG) { doPost(req, resp); } else { super.doGet(req, resp); } } protected String getParameter(HttpServletRequest req, String parameter) throws ServletException { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { if (DEBUG) { StringBuilder parameters = new StringBuilder(); @SuppressWarnings("unchecked") Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); String param = req.getParameter(name); parameters.append(name).append("=").append(param).append("\n"); } logger.fine("parameters: " + parameters); } throw new ServletException("Parameter " + parameter + " not found"); } return value.trim(); } protected String getParameter(HttpServletRequest req, String parameter, String defaultValue) { String value = req.getParameter(parameter); if (isEmptyOrNull(value)) { value = defaultValue; } return value.trim(); } protected void setSuccess(HttpServletResponse resp) { setSuccess(resp, 0); } protected void setSuccess(HttpServletResponse resp, int size) { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.setContentLength(size); } protected boolean isEmptyOrNull(String value) { return value == null || value.trim().length() == 0; } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.EntityNotFoundException; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import java.util.logging.Logger; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * Context initializer that loads the API key from the App Engine datastore. */ public class ApiKeyInitializer implements ServletContextListener { static final String ATTRIBUTE_ACCESS_KEY = "apiKey"; private static final String ENTITY_KIND = "Settings"; private static final String ENTITY_KEY = "MyKey"; private static final String ACCESS_KEY_FIELD = "ApiKey"; private final Logger logger = Logger.getLogger(getClass().getName()); public void contextInitialized(ServletContextEvent event) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY); Entity entity; try { entity = datastore.get(key); } catch (EntityNotFoundException e) { entity = new Entity(key); // NOTE: it's not possible to change entities in the local server, so // it will be necessary to hardcode the API key below if you are running // it locally. entity.setProperty(ACCESS_KEY_FIELD, "replace_this_text_by_your_Simple_API_Access_key"); datastore.put(entity); logger.severe("Created fake key. Please go to App Engine admin " + "console, change its value to your API Key (the entity " + "type is '" + ENTITY_KIND + "' and its field to be changed is '" + ACCESS_KEY_FIELD + "'), then restart the server!"); } String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD); event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey); } public void contextDestroyed(ServletContextEvent event) { } }
Java
/* * Copyright 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gcm.demo.server; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet that adds display number of devices and button to send a message. * <p> * This servlet is used just by the browser (i.e., not device) and contains the * main page of the demo app. */ @SuppressWarnings("serial") public class HomeServlet extends BaseServlet { static final String ATTRIBUTE_STATUS = "status"; /** * Displays the existing messages and offer the option to send a new one. */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<head>"); out.print(" <title>GCM Demo</title>"); out.print(" <link rel='icon' href='favicon.png'/>"); out.print("</head>"); String status = (String) req.getAttribute(ATTRIBUTE_STATUS); if (status != null) { out.print(status); } int total = Datastore.getTotalDevices(); if (total == 0) { out.print("<h2>No devices registered!</h2>"); } else { out.print("<h2>" + total + " device(s) registered!</h2>"); out.print("<form name='form' method='POST' action='sendAll'>"); out.print("<input type='submit' value='Send Message' />"); out.print("</form>"); } out.print("</body></html>"); resp.setStatus(HttpServletResponse.SC_OK); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { doGet(req, resp); } }
Java
package org.annoflow.javassist; import java.util.List; import org.annoflow.filter.Filter; import org.annoflow.filter.FilterPoint; import org.annoflow.policy.PolicyType; import org.annoflow.policy.Policy; import org.annoflow.policy.TopSecret; import org.apache.log4j.Logger; import javassist.CannotCompileException; import javassist.ClassPool; import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.NotFoundException; import javassist.Translator; public class AnnoTranslator implements Translator { private AnnoCustomExprEditor cusExpr; private Logger logger = Logger.getLogger(AnnoTranslator.class); public AnnoTranslator(ConfigParser current) { List<CommandInterface> editConfigs = current.getCommands(); cusExpr = new AnnoCustomExprEditor(editConfigs); } @Override public void onLoad(ClassPool pool, String className) throws NotFoundException, CannotCompileException { logger.info("Loading Class " + className); CtClass clazz = pool.get(className); try { rewriteFilters(clazz); addPolicies(clazz, pool); cusExpr.staticEdits(clazz); if (!clazz.isFrozen() && clazz.getPackageName().startsWith("dummy.")) { clazz.instrument(cusExpr); } } catch (ClassNotFoundException e) { logger.error(e); } } private void rewriteFilters(CtClass clazz) throws ClassNotFoundException { try { for (CtMethod method : clazz.getDeclaredMethods()) { for (Object annotation : method.getAnnotations()) { if (annotation instanceof Filter) { logger.info("Found Filter annotation on " + method.getName() + " in class " + clazz.getName()); Filter filterAnno = (Filter) annotation; String annoType = filterAnno.type().getName(); @SuppressWarnings("unchecked") Class<FilterPoint> annoClazz = (Class<FilterPoint>)Class .forName(annoType); FilterPoint fPoint = annoClazz.newInstance(); String filterCode = fPoint.getFilterCode(); String returnFilterCode = fPoint.getReturnFilterCode(); // System.err.println(filterCode); //method.insertBefore("org.annoflow.audit.ContextTracker.getInstance().setFilterContext($class);"); if (filterCode != null) method.insertBefore("org.annoflow.audit.ContextTracker.getInstance().setFilterContext($class);"+filterCode+"org.annoflow.audit.ContextTracker.getInstance().clear();"); if (returnFilterCode != null) method.insertAfter("org.annoflow.audit.ContextTracker.getInstance().setFilterContext($class);"+returnFilterCode+"org.annoflow.audit.ContextTracker.getInstance().clear();", true); //Treat as "finally" block } } } } catch (IllegalAccessException e) { logger.error("Could not call filter default constructor", e); } catch (InstantiationException e) { logger.error("Exception thrown inside of constructor", e); } catch (CannotCompileException e) { logger.error("The replacement text is no good!", e); } } private void addPolicies(CtClass clazz, ClassPool pool) { try { for (Object annotation : clazz.getAnnotations()) { String policyClass = null; if (annotation instanceof Policy) { logger.info("Found Policy annotation on " + clazz.getName() + " class"); Policy policy = (Policy) annotation; policyClass = policy.policy().getName(); } else if (annotation instanceof TopSecret) { policyClass = "org.annoflow.policy.TopSecretPolicy"; logger.info("Found TopSecret annotation on " + clazz.getName() + " class"); } if (policyClass != null) { @SuppressWarnings("unchecked") Class<PolicyType> pClazz = (Class<PolicyType>) Class .forName(policyClass); String src = pClazz.newInstance().getPolicyCode(); CtConstructor staticConstructor = clazz .makeClassInitializer(); if (staticConstructor != null) { staticConstructor.insertBefore(src); } // for (CtConstructor construct : clazz.getConstructors()) { // // System.err.println(src); // construct.insertBefore(src); // } } } } catch (IllegalAccessException e) { logger.error("Could not call policy default constructor", e); } catch (InstantiationException e) { logger.error("Exception thrown inside of constructor", e); } catch (ClassNotFoundException e) { logger.error("Could not find specified class", e); } catch (CannotCompileException e) { logger.error( "Could not compile the modifications for Policy cutin", e); } catch (SecurityException e) { logger.error( "Could not construct a policy object for the class", e); } catch (IllegalArgumentException e) { logger.error("The arguments to the constructor are incorrect", e); } } @Override public void start(ClassPool pool) throws NotFoundException, CannotCompileException { } }
Java
package org.annoflow.javassist; import org.apache.log4j.Logger; public class MalformedConfigurationException extends Exception { protected Logger logger = Logger.getLogger(MalformedConfigurationException.class); /** * */ private static final long serialVersionUID = 1L; public MalformedConfigurationException(String message) { super(message); logger.error(message); } }
Java
package org.annoflow.javassist; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import javassist.expr.Cast; import javassist.expr.ConstructorCall; import javassist.expr.Expr; import javassist.expr.ExprEditor; import javassist.expr.FieldAccess; import javassist.expr.Handler; import javassist.expr.Instanceof; import javassist.expr.MethodCall; import javassist.expr.NewArray; import javassist.expr.NewExpr; import org.apache.log4j.Logger; import org.annoflow.filter.FilterPoint; import org.annoflow.javassist.AbstractCommand.SignatureType; import org.annoflow.policy.PolicyType; import org.annoflow.policy.Policy; /** * The Class CustomExprEditor. This class is responsible for actually editing * the */ public class AnnoCustomExprEditor extends ExprEditor { protected Logger logger = Logger.getLogger(CustomExprEditor.class); private abstract class PrivlegedJavassistAction implements PrivilegedExceptionAction<String> { protected Object context; public void setContext(Object context) { this.context = context; } } Map<SignatureType, Map<String, List<CommandInterface>>> ExpressionNameToCommand; /** * Instantiates a new custom expr editor. from a list of commands. These * commands are stored in seperate lists to be executed on method calls and * expressions being translated. * * @param editConfigs * commands to drive the configuration. */ public AnnoCustomExprEditor(List<CommandInterface> editConfigs) { ExpressionNameToCommand = new HashMap<SignatureType, Map<String, List<CommandInterface>>>(); for (CommandInterface curCommand : editConfigs) { // CommandInterface curCommand = commandIter.next(); Map<String, List<CommandInterface>> sigMap = ExpressionNameToCommand .get(curCommand.getSignatureType()); if (sigMap == null) { sigMap = new HashMap<String, List<CommandInterface>>(); ExpressionNameToCommand.put(curCommand.getSignatureType(), sigMap); } List<CommandInterface> commands = sigMap.get(curCommand .getSignature()); if (commands == null) { commands = new LinkedList<CommandInterface>(); sigMap.put(curCommand.getSignature(), commands); } commands.add(curCommand); } } /** * this method is for static edits to a class. These happen once and are not * iterated. * * @param clazz * the clazz to be edited */ public synchronized void staticEdits(CtClass clazz) { Map<String, List<CommandInterface>> sigTypeMap = ExpressionNameToCommand .get(SignatureType.METHODBODY); performStaticEdits(clazz, sigTypeMap); sigTypeMap = ExpressionNameToCommand .get(SignatureType.STATICDEFINITION); performStaticEdits(clazz, sigTypeMap); } private void performStaticEdits(CtClass clazz, Map<String, List<CommandInterface>> sigTypeMap) { if (sigTypeMap != null) { for (CtMethod method : clazz.getDeclaredMethods()) { String methodName = method.getLongName(); int nameStart = method.getLongName() .substring(0, method.getLongName().indexOf('(')) .lastIndexOf('.'); methodName = methodName.substring(nameStart + 1); List<CommandInterface> listOfCommands = sigTypeMap .get(methodName); if (listOfCommands != null) { for (CommandInterface curCommand : listOfCommands) { // CommandInterface curCommand = iterCommand.next(); try { curCommand.translate(method, methodName); } catch (Exception e) { logger.error( "Could not perform Static edit: [" + methodName + "," + curCommand.getSignature() + "]", e); } } } } } } /** * Conversion of an Expr. * * @param ccall * the expression ccall * @param commandList * the list of commands to use to perform the edit. * @param expressionName * the name of the expression being edited. */ private void convert(Expr ccall, List<CommandInterface> commandList, boolean isSuper) { if (commandList != null) { for (CommandInterface curCommand : commandList) { try { curCommand.translate(ccall, isSuper); } catch (MalformedCommandException e) { logger.error( "The command is not written correctly please revise it: " + curCommand.toString(), e); } catch (CannotCompileException e) { logger.error("Could not compile the replacement text: " + curCommand.getReplacement(), e); } } } else { if(ccall instanceof MethodCall && !(ccall instanceof ConstructorCall)) { try { boolean rewrite = true; MethodCall call = (MethodCall)ccall; try { call.getMethod().getAnnotation(Policy.class); }catch (ClassNotFoundException e) { rewrite = false; } CtClass clazz = call.getMethod().getDeclaringClass(); if(clazz.getName().startsWith("org.annoflow") || clazz.getName().startsWith("javassist") || clazz.getName().startsWith("java")) { rewrite = false; } if(rewrite) call.replace("org.annoflow.audit.ContextTracker.getInstance().setCallerContext(\""+ call.getEnclosingClass().getName()+"\");$_=$proceed($$);org.annoflow.audit.ContextTracker.getInstance().clear();"); } catch (CannotCompileException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public List<CommandInterface> getCommandList(SignatureType sigType, String signature) { Map<String, List<CommandInterface>> callToCommand = ExpressionNameToCommand .get(sigType); if (callToCommand != null) { return callToCommand.get(signature); } return null; } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.Handler) */ public void edit(Handler ccall) { /* * try { PrivlegedJavassistAction action = new * PrivlegedJavassistAction() { * * @Override public String run() throws NotFoundException { CtClass type * = ((Handler)context).getType(); if(type ==null) { return ""; } return * type.getName(); } * * }; action.setContext(ccall); String constName = * AccessController.doPrivileged(action); * logger.trace("Attempting to rewrite "+constName); //String handlerSig * = ccall.getType().getName(); convert(ccall, * getCommandList(SignatureType.HANDLER, constName), false); } catch * (PrivilegedActionException e) { * logger.error("Exception occured rewriting a Handler call in " * +ccall.getFileName()); e.printStackTrace(); } */ } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.Cast) */ public void edit(Cast ccall) { /* * try { PrivlegedJavassistAction action = new * PrivlegedJavassistAction() { * * @Override public String run() throws NotFoundException { return * ((Cast)context).getType().getName(); } * * }; action.setContext(ccall); String constName = * AccessController.doPrivileged(action); * logger.trace("Attempting to rewrite "+constName); convert(ccall, * getCommandList(SignatureType.CAST, constName), false); } catch * (PrivilegedActionException e) { * logger.error("Exception occured rewriting a Cast call in " * +ccall.getFileName()); e.printStackTrace(); } */ } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.Instanceof) */ public void edit(Instanceof ccall) { /* * try { PrivlegedJavassistAction action = new * PrivlegedJavassistAction() { * * @Override public String run() throws NotFoundException { return * ((Instanceof)context).getType().getName(); } * * }; action.setContext(ccall); String constName = * AccessController.doPrivileged(action); * logger.trace("Attempting to rewrite "+constName); convert(ccall, * getCommandList(SignatureType.INSTANCEOF, constName), false); } catch * (PrivilegedActionException e) { * logger.error("Exception occured rewriting a Instance of call in " * +ccall.getFileName()); e.printStackTrace(); } */ } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.FieldAccess) */ public void edit(FieldAccess ccall) { try { Object[] annotations = ccall.getField().getAnnotations(); for (Object anno : annotations) { if (anno instanceof Policy) { Policy annoPolicy = (Policy) anno; Class<? extends PolicyType> policyClass = annoPolicy .policy(); PolicyType policy = policyClass.newInstance(); if (ccall.isWriter()) { logger.info("Adding policy to write op on field " + ccall.getFieldName() + " in class " + ccall.getEnclosingClass().getName()); ccall.replace("$_=$proceed($$);org.annoflow.policy.PolicyManager.addFieldPolicy(" + ccall.getFieldName() + "," + "this" + "," + policy.getClass().getCanonicalName() + ".class);"); } } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (CannotCompileException e) { e.printStackTrace(); } // TODO: This probably does not work! If you attempt to access the field // in a super class this may fall apart. /* * try { action.setClass(ccall.getType()); String fieldName = * ccall.getField().getName(); convert(ccall, * getCommandList(SignatureType.FIELDACCESS, fieldName), false); } catch * (NotFoundException e) { * System.err.println("Could not find class for array type"); * e.printStackTrace(); } */ } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.NewArray) */ public void edit(NewArray ccall) { /* * try { PrivlegedJavassistAction action = new * PrivlegedJavassistAction() { * * @Override public String run() throws NotFoundException { return * ((NewArray)context).getComponentType().getName(); } * * }; action.setContext(ccall); String constName = * AccessController.doPrivileged(action); * logger.trace("Attempting to rewrite "+constName); convert(ccall, * getCommandList(SignatureType.NEWARRAY, constName), false); } catch * (PrivilegedActionException e) { * logger.error("Exception occured rewriting a NewArray call in " * +ccall.getFileName()); e.printStackTrace(); } */ } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.MethodCall) */ public void edit(MethodCall ccall) { try { PrivlegedJavassistAction action = new PrivlegedJavassistAction() { @Override public String run() throws NotFoundException { return ((MethodCall) context).getMethod().getLongName(); } }; action.setContext(ccall); String constName = (String) AccessController.doPrivileged(action); logger.trace("Attempting to rewrite " + constName); convert(ccall, getCommandList(SignatureType.METHODCALL, constName), ccall.isSuper()); } catch (PrivilegedActionException e) { logger.error("Exception occured rewriting a MethodCall call in " + ccall.getFileName(), e); } } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.ConstructorCall) */ public void edit(ConstructorCall ccall) { try { PrivlegedJavassistAction action = new PrivlegedJavassistAction() { @Override public String run() throws NotFoundException { return ((ConstructorCall) context).getConstructor() .getLongName(); } }; action.setContext(ccall); String constName = AccessController.doPrivileged(action); logger.trace("Attempting to rewrite " + constName); convert(ccall, getCommandList(SignatureType.CONSTRUCTORCALL, constName), ccall.isSuper()); } catch (PrivilegedActionException e) { logger.error( "Exception occured rewriting a ConstructorCall call in " + ccall.getFileName(), e); } } /* * (non-Javadoc) * * @see javassist.expr.ExprEditor#edit(javassist.expr.NewExpr) */ public void edit(NewExpr ccall) { try { PrivlegedJavassistAction action = new PrivlegedJavassistAction() { @Override public String run() throws NotFoundException { return ((NewExpr) context).getConstructor().getLongName(); } }; action.setContext(ccall); String constName = AccessController.doPrivileged(action); logger.trace("Attempting to rewrite " + constName); List<CommandInterface> commands = getCommandList( SignatureType.NEWEXPR, constName); if (commands != null) { convert(ccall, commands, false); } else if(ccall.getEnclosingClass().hasAnnotation(Policy.class)){ checkPolicy(ccall); } } catch (PrivilegedActionException e) { logger.error("Exception occured rewriting a NewExpr call in " + ccall.getFileName(), e); } catch (CannotCompileException e2) { logger.error( "Exception occured when adding the policy check to the new Expression", e2); } } private void checkPolicy(NewExpr expr) throws CannotCompileException { expr.replace("$_=$proceed($$);org.annoflow.audit.ContextTracker.getInstance().setCallerContext(\""+expr.getEnclosingClass().getName()+"\");org.annoflow.policy.PolicyManager.addObjectPolicy($_);org.annoflow.audit.ContextTracker.getInstance().clear();"); } }
Java
package org.annoflow.javassist; import java.util.List; import javassist.CannotCompileException; import javassist.CtClass; import javassist.CtMethod; import javassist.NotFoundException; import javassist.expr.Expr; public class InsertAfter extends AbstractCommand { // private class ClassOutline // { // public Map<String,CtMethod> declaredMethods; // public ClassOutline(CtClass myClazz) // { // declaredMethods = new HashMap<String,CtMethod>(); // outline(myClazz); // } // private void outline(CtClass clazz) // { // //System.out.println("\nAnalyzing "+ clazz.getName()); // for(CtMethod method : clazz.getDeclaredMethods()) // { // declaredMethods.put(method.getName(), method); // } // } // public boolean isDeclared(String methodName) // { // if(declaredMethods.get(methodName) == null) // return false; // return true; // } // } // public static Map<String, ClassOutline> inheritanceMap = new HashMap<String, ClassOutline>(); // private static boolean rewriteNeeded(CtClass clazz, String methodName) // { // try // { // if (clazz != null) // { // // VM currentVM = VM.currentVM(); // // ClassOutline cOutline = inheritanceMap.get(clazz.getName()); // if (VM.currentVM().isLocalClass(clazz.getName())) // { // for (CtBehavior behavior : clazz.getDeclaredBehaviors()) // { // String behaviorName = behavior.getLongName(); // if (behaviorName.endsWith(methodName)) // { // return false; // } // } // CtClass superClazz = null; // superClazz = clazz.getSuperclass(); // return rewriteNeeded(superClazz, methodName); // // } // else // { // return true; // } // } // } // catch (NotFoundException e) // { // ; // } // return true; // } private static boolean inSuperChain(CtClass declaringClass, String superName) { if (declaringClass != null) { try { if (declaringClass.getName().equals(superName)) { return true; } else { return inSuperChain(declaringClass.getSuperclass(), superName); } } catch (NotFoundException e) { ; } } return false; } protected InsertAfter(List<String> argList) throws MalformedCommandException { super(argList); } @Override public void translate(Expr call, boolean isSuper) throws MalformedCommandException, CannotCompileException { // TODO Auto-generated method stub } public String getReplacement() { return unParsedArgs.get(4).substring(1, unParsedArgs.get(4).length() - 1); } @Override public void translate(CtMethod member, String expressionName) throws MalformedCommandException, CannotCompileException { if (expressionName.equals(getSignature()) && inSuperChain(member.getDeclaringClass(), unParsedArgs.get(3))) { // String replacement = getReplacement(); member.insertAfter(getReplacement()); } } }
Java