code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
// 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.client.presenter; import com.google.common.collect.Lists; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.view.CapabilityDetailsView; 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.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.Project; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; import java.util.Collection; import java.util.List; /** * Presenter for the details of a single capability. * * @author jimr@google.com (Jim Reardon) */ public class CapabilityDetailsPresenter extends BasePagePresenter implements CapabilityDetailsView.Presenter { protected final Project project; protected final ProjectRpcAsync projectService; protected final UserRpcAsync userService; protected final DataRpcAsync dataService; protected final CapabilityDetailsView view; protected String pageData; private Long capabilityId; public CapabilityDetailsPresenter(Project project, ProjectRpcAsync projectService, DataRpcAsync dataService, UserRpcAsync userService, CapabilityDetailsView view) { this.project = project; this.projectService = projectService; this.dataService = dataService; this.userService = userService; this.view = view; view.setPresenter(this); } @Override public void refreshView() { final long projectId = project.getProjectId(); // Tell view to expect an entire reload of data. view.reset(); userService.hasEditAccess(projectId, new TaCallback<Boolean>("Querying user permissions") { @Override public void onSuccess(Boolean result) { if (result == true) { view.makeEditable(); } } }); projectService.getProjectAttributes(projectId, new TaCallback<List<Attribute>>("Querying Attributes") { @Override public void onSuccess(List<Attribute> result) { view.setAttributes(result); } }); projectService.getLabels(projectId, new TaCallback<List<AccLabel>>("Querying Components") { @Override public void onSuccess(List<AccLabel> result) { Collection<String> labels = Lists.newArrayList(); for (AccLabel l : result) { labels.add(l.getLabelText()); } view.setProjectLabels(labels); } }); projectService.getProjectComponents(projectId, new TaCallback<List<Component>>("Querying Components") { @Override public void onSuccess(List<Component> result) { view.setComponents(result); } }); projectService.getCapabilityById(projectId, capabilityId, new TaCallback<Capability>("Querying capability") { @Override public void onSuccess(Capability result) { view.setCapability(result); } }); dataService.isSignedOff(AccElementType.CAPABILITY, capabilityId, new TaCallback<Boolean>("Getting signoff status") { @Override public void onSuccess(Boolean result) { view.setSignoff(result == null ? false : result); } }); dataService.getProjectBugsById(projectId, new TaCallback<List<Bug>>("Querying Bugs") { @Override public void onSuccess(List<Bug> result) { view.setBugs(result); } }); dataService.getProjectTestCasesById(projectId, new TaCallback<List<TestCase>>("Querying Tests") { @Override public void onSuccess(List<TestCase> result) { view.setTests(result); } }); dataService.getProjectCheckinsById(projectId, new TaCallback<List<Checkin>>("Querying Checkins") { @Override public void onSuccess(List<Checkin> result) { view.setCheckins(result); } }); } @Override public void assignBugToCapability(long capabilityId, long bugId) { dataService.updateBugAssociations(bugId, -1, -1, capabilityId, new TaCallback<Void>("assigning bug to capability")); } @Override public void assignCheckinToCapability(long capabilityId, long checkinId) { dataService.updateCheckinAssociations(checkinId, -1, -1, capabilityId, new TaCallback<Void>("assigning checkin to capability")); } @Override public void assignTestCaseToCapability(long capabilityId, long testId) { dataService.updateTestAssociations(testId, -1, -1, capabilityId, new TaCallback<Void>("assigning test to capability")); } @Override public void refreshView(String pageData) { try { capabilityId = Long.parseLong(pageData); } catch (NumberFormatException e) { Window.alert("Cannot refresh capability details page, invalid capbility ID."); } refreshView(); } @Override public Widget getView() { return view.asWidget(); } @Override public void updateCapability(Capability capability) { projectService.updateCapability(capability, new TaCallback<Void>("updating capability")); } @Override public void setSignoff(long capabilityId, boolean isSignedOff) { dataService.setSignedOff(project.getProjectId(), AccElementType.CAPABILITY, capabilityId, isSignedOff, new TaCallback<Void>("setting signoff status")); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/presenter/CapabilityDetailsPresenter.java
Java
asf20
6,761
// 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.client.presenter; import com.google.common.collect.Maps; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.view.ConfigureFiltersView; 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.Filter; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import java.util.HashMap; import java.util.List; /** * Presenter for Filter list and creating filters. * * @author jimr@google.com (Jim Reardon) */ public class ConfigureFiltersPresenter extends BasePagePresenter implements TaPagePresenter, ConfigureFiltersView.Presenter { private final Project project; private final DataRpcAsync dataService; private final ProjectRpcAsync projectService; private final ConfigureFiltersView view; public ConfigureFiltersPresenter(Project project, DataRpcAsync dataService, ProjectRpcAsync projectService, ConfigureFiltersView view) { this.project = project; this.dataService = dataService; this.projectService = projectService; this.view = view; refreshView(); } @Override public Widget getView() { return view.asWidget(); } @Override public void refreshView() { view.setPresenter(this); dataService.getFilters(project.getProjectId(), new TaCallback<List<Filter>>("Getting filters") { @Override public void onSuccess(List<Filter> result) { view.setFilters(result); } }); projectService.getProjectAttributes(project.getProjectId(), new TaCallback<List<Attribute>>("Getting attributes") { @Override public void onSuccess(List<Attribute> result) { HashMap<String, Long> map = Maps.newHashMap(); for (Attribute attribute : result) { map.put(attribute.getName(), attribute.getAttributeId()); } view.setAttributes(map); } }); projectService.getProjectComponents(project.getProjectId(), new TaCallback<List<Component>>("Getting components") { @Override public void onSuccess(List<Component> result) { HashMap<String, Long> map = Maps.newHashMap(); for (Component component : result) { map.put(component.getName(), component.getComponentId()); } view.setComponents(map); } }); projectService.getProjectCapabilities(project.getProjectId(), new TaCallback<List<Capability>>("Getting capabilities") { @Override public void onSuccess(List<Capability> result) { HashMap<String, Long> map = Maps.newHashMap(); for (Capability capability : result) { map.put(capability.getName(), capability.getCapabilityId()); } view.setCapabilities(map); } }); } @Override public void addFilter(final Filter newFilter) { newFilter.setParentProjectId(project.getProjectId()); dataService.addFilter(newFilter, new TaCallback<Long>("Adding new filter") { @Override public void onSuccess(Long result) { newFilter.setId(result); refreshView(); } }); } @Override public void deleteFilter(Filter filterToDelete) { dataService.removeFilter(filterToDelete, new TaCallback<Void>("Deleting filter") { @Override public void onSuccess(Void result) { refreshView(); } }); } @Override public void updateFilter(Filter filterToUpdate) { dataService.updateFilter(filterToUpdate, TaCallback.getNoopCallback()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/presenter/ConfigureFiltersPresenter.java
Java
asf20
4,719
// 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.client.presenter; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.view.ConfigureDataView; 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.Project; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import java.util.List; /** * Presenter for the Configure Data page. * * @author chrsmith@google.com (Chris Smith) */ public class ConfigureDataPresenter extends BasePagePresenter implements TaPagePresenter, ConfigureDataView.Presenter { private final Project project; private final DataRpcAsync dataService; private final ConfigureDataView view; public ConfigureDataPresenter( Project project, DataRpcAsync rpcService, ConfigureDataView view) { this.project = project; this.dataService = rpcService; this.view = view; refreshView(); } @Override public void refreshView() { view.setPresenter(this); dataService.getDataSources( new TaCallback<List<DataSource>>("Getting data source options") { @Override public void onSuccess(List<DataSource> result) { view.setDataSources(result); } }); dataService.getProjectRequests(project.getProjectId(), new TaCallback<List<DataRequest>>("Getting data requests") { @Override public void onSuccess(List<DataRequest> result) { view.setDataRequests(result); } }); } @Override public void addDataRequest(final DataRequest newRequest) { newRequest.setParentProjectId(project.getProjectId()); dataService.addDataRequest(newRequest, new TaCallback<Long>("Updating data request") { @Override public void onSuccess(Long result) { newRequest.setRequestId(result); refreshView(); } }); } @Override public void updateDataRequest(DataRequest requestToUpdate) { dataService.updateDataRequest(requestToUpdate, TaCallback.getNoopCallback()); } @Override public void deleteDataRequest(DataRequest requestToDelete) { dataService.removeDataRequest(requestToDelete, new TaCallback<Void>("Deleting data request") { @Override public void onSuccess(Void result) { refreshView(); } }); } @Override public Widget getView() { return view.asWidget(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/presenter/ConfigureDataPresenter.java
Java
asf20
3,268
// 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.client.presenter; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.view.RiskView; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; /** * Presenter for viewing a project's known risk, that is outstanding risk minus mitigations. * * @author chrsmith@google.com (Chris Smith) */ public class KnownRiskPresenter extends RiskPresenter implements TaPagePresenter { public KnownRiskPresenter( Project project, ProjectRpcAsync projectService, RiskView view) { super(project, projectService, view); refreshView(); } @Override public void refreshView() { refreshBaseView(); } @Override public Widget getView() { return view.asWidget(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/presenter/KnownRiskPresenter.java
Java
asf20
1,479
// 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.client.presenter; import com.google.common.collect.Lists; import com.google.gwt.event.shared.EventBus; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedEvent; import com.google.testing.testify.risk.frontend.client.event.ProjectHasNoElementsEvent; import com.google.testing.testify.risk.frontend.client.view.AttributesView; 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.Project; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; import java.util.Collection; import java.util.List; /** * Presenter for the Attributes page. * * @author jimr@google.com (Jim Reardon) */ public class AttributesPresenter extends BasePagePresenter implements AttributesView.Presenter, TaPagePresenter { private final Project project; private final ProjectRpcAsync projectService; private final UserRpcAsync userService; private final DataRpcAsync dataService; private final AttributesView view; private final EventBus eventBus; private final Collection<String> projectLabels = Lists.newArrayList(); /** * Constructs the Attributes page presenter. */ public AttributesPresenter( Project project, ProjectRpcAsync projectService, UserRpcAsync userService, DataRpcAsync dataService, AttributesView view, EventBus eventBus) { this.project = project; this.projectService = projectService; this.userService = userService; this.dataService = dataService; this.view = view; this.eventBus = eventBus; refreshView(); } /** * Query the database for project information and populate UI fields. */ @Override public void refreshView() { view.setPresenter(this); userService.hasEditAccess(project.getProjectId(), new TaCallback<Boolean>("checking user access") { @Override public void onSuccess(Boolean result) { if (result) { view.enableEditing(); } } }); projectService.getProjectAttributes(project.getProjectId(), new TaCallback<List<Attribute>>("loading attributes") { @Override public void onSuccess(List<Attribute> result) { // If the project has no attributes, we need to broadcast it. if (result.size() == 0) { eventBus.fireEvent( new ProjectHasNoElementsEvent(project, AccElementType.ATTRIBUTE)); } view.setProjectAttributes(result); } }); projectService.getLabels(project.getProjectId(), new TaCallback<List<AccLabel>>("loading labels") { @Override public void onSuccess(List<AccLabel> result) { for (AccLabel l : result) { projectLabels.add(l.getLabelText()); } view.setProjectLabels(projectLabels); } }); dataService.getSignoffsByType(project.getProjectId(), AccElementType.ATTRIBUTE, new TaCallback<List<Signoff>>("loading signoff details") { @Override public void onSuccess(List<Signoff> results) { view.setSignoffs(results); } }); } /** Returns the underlying view. */ @Override public Widget getView() { return view.asWidget(); } @Override public long getProjectId() { return project.getProjectId(); } /** * Adds a new Attribute to the data store. */ @Override public void createAttribute(final Attribute attribute) { projectService.createAttribute(attribute, new TaCallback<Long>("creating attribute") { @Override public void onSuccess(Long result) { attribute.setAttributeId(result); eventBus.fireEvent(new ProjectElementAddedEvent(attribute)); refreshView(); } }); } /** * Updates the given attribute in the database. */ @Override public void updateAttribute(Attribute attributeToUpdate) { projectService.updateAttribute(attributeToUpdate, new TaCallback<Attribute>("updating attribute") { @Override public void onSuccess(Attribute result) { view.refreshAttribute(result); } }); } @Override public void updateSignoff(Attribute attribute, boolean newSignoff) { dataService.setSignedOff(attribute.getParentProjectId(), AccElementType.ATTRIBUTE, attribute.getAttributeId(), newSignoff, TaCallback.getNoopCallback()); } /** * Removes the given attribute from the Project. */ @Override public void removeAttribute(Attribute attributeToRemove) { projectService.removeAttribute(attributeToRemove, new TaCallback<Void>("deleting attribute") { @Override public void onSuccess(Void result) { refreshView(); } }); } @Override public void reorderAttributes(List<Long> newOrder) { projectService.reorderAttributes( project.getProjectId(), newOrder, new TaCallback<Void>("reordering attributes") { @Override public void onSuccess(Void result) { refreshView(); } }); } @Override public ProjectRpcAsync getProjectService() { return projectService; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/presenter/AttributesPresenter.java
Java
asf20
6,431
// 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.client.view; import com.google.gwt.user.client.ui.Widget; 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 java.util.List; /** * View on top of any user interface for visualizing a project's Risk or Risk Mitigations. * * @author chrsmith@google.com (Chris Smith) */ public interface RiskView { /** * Initializes user interface elements with the given components. */ public void setComponents(List<Component> components); /** * Initializes user interface elements with the given attributes. */ public void setAttributes(List<Attribute> attributes); /** * Notifies the view of all Project Components. */ public void setCapabilities(List<Capability> capabilities); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/RiskView.java
Java
asf20
1,600
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.presenter.TaPagePresenter; 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.TestCase; import java.util.Collection; import java.util.List; /** * View on top of the CapabilityDetails page. * * @author jimr@google.com (Jim Reardon) */ public interface CapabilityDetailsView { /** * Presenter interface for this view. */ public interface Presenter extends TaPagePresenter { public void assignBugToCapability(long capabilityId, long bugId); public void assignCheckinToCapability(long capabilityId, long checkinId); public void assignTestCaseToCapability(long capabilityId, long testId); public void updateCapability(Capability capability); public void setSignoff(long capabilityId, boolean isSignedOff); } public void setAttributes(List<Attribute> attributes); public void setBugs(List<Bug> bugs); public void setComponents(List<Component> components); public void setCapability(Capability capability); public void setTests(List<TestCase> tests); public void setCheckins(List<Checkin> checkins); public void setSignoff(boolean signoff); public void setProjectLabels(Collection<String> labels); public void setPresenter(Presenter presenter); /** * Reset clears all stored data. Call before refresh, or setting new data, * to avoid staggering updates. */ public void reset(); public void makeEditable(); public void refresh(); public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/CapabilityDetailsView.java
Java
asf20
2,526
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import java.util.Collection; import java.util.List; /** * View on top of the ProjectAttributes page. * * @author chrsmith@google.com (Chris Smith) */ public interface AttributesView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * @return the ProjectID for the project the View is displaying. */ long getProjectId(); /** * Notifies the Presenter that a new Attribute has been created. */ public void createAttribute(Attribute attribute); /** * Updates the given Attribute in the database. */ public void updateAttribute(Attribute attributeToUpdate); public void updateSignoff(Attribute attribute, boolean newSignoff); /** * Removes the given Attribute from the Project. */ public void removeAttribute(Attribute attributeToRemove); /** * Reorders the project's list of Attributes. */ public void reorderAttributes(List<Long> newOrder); /** Get the ProjectService associated with the presenter. */ public ProjectRpcAsync getProjectService(); } /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** * Initialize user interface elements with the given set of Attributes. */ public void setProjectAttributes(List<Attribute> attributes); /** Update a single attribute */ public void refreshAttribute(Attribute attribute); /** All of this project's labels. Used for autocomplete drop-down. */ public void setProjectLabels(Collection<String> projectLabels); /** * Data on which elements have been signed off. */ public void setSignoffs(List<Signoff> signoffs); /** * Updates the view to enable editing of attribute data. */ public void enableEditing(); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/AttributesView.java
Java
asf20
2,877
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Component; import java.util.List; /** * View for a Component widget. * {@See com.google.testing.testify.risk.frontend.model.Component} * * @author chrsmith@google.com (Chris Smith) */ public interface ComponentView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * Returns the project ID of the target Component. */ public long getProjectId(); /** * Returns the Component ID of the target Component. */ public long getComponentId(); public void updateSignoff(boolean newSignoff); public void onDescriptionEdited(String description); /** * Called when the user renames the given component. */ public void onRename(String newComponentName); /** * Called when the user deletes the given Component. */ public void onRemove(); /** * Called when the user updates a label. */ public void onUpdateLabel(AccLabel label, String newText); /** * Called when the user adds a new Label. */ public void onAddLabel(String label); /** * Called when the user removes a label. */ public void onRemoveLabel(AccLabel label); public void refreshView(Component component); /** Requests the presenter refresh the view's controls. */ public void refreshView(); } /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** * Set the UI to display the Component's name. */ public void setComponentName(String componentName); public void setDescription(String description); public void setSignedOff(boolean signedOff); /** * Set the UI to display the Component's ID. */ public void setComponentId(Long componentId); /** * Set the UI to display the given Component labels. */ public void setComponentLabels(List<AccLabel> componentLabels); /** * Updates the view to enable editing of attribute data. */ public void enableEditing(); /** * Hides the Widget so it is no longer visible. (Typically after the Component has been deleted.) */ public void hide(); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/ComponentView.java
Java
asf20
3,132
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; /** * View on top of the ProjectSettings Widget. * * @author chrsmith@google.com (Chris Smith) */ public interface ProjectSettingsView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * @return the ProjectID for the project the View is displaying. */ long getProjectId(); /** * @return a handle to the Presenter's ProjectService serverlet. Ideally this should be hidden. */ ProjectRpcAsync getProjectService(); /** * Updates the project name, summary, and description get updated in one batch action. */ void onUpdateProjectInfoClicked( String projectName, String projectDescription, List<String> projectOwners, List<String> projectEditors, List<String> projectViewers, boolean isPublicalyVisible); /** * Deletes the Project. Proceed with caution. */ public void removeProject(); } /** * Shows the "project saved" panel. */ public void showSaved(); /** * Updates the view to enable editing of project data. (Security will still be checked in the * backend servlet.) */ public void enableProjectEditing(ProjectAccess userAccessLevel); /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** * Initialize user interface elements with the given project settings. */ public void setProjectSettings(Project projectSettings); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/ProjectSettingsView.java
Java
asf20
2,583
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.FilterOption; import java.util.List; import java.util.Map; /** * View for a Filter. * * @author jimr@google.com (Jim Reardon) */ public interface FilterView { /** Interface for notifying the presenter about changes to this view. */ public interface Presenter { /** Called when the options for this filter are updated. */ public void onUpdate(List<FilterOption> newOptions, String conjunction, Long attribute, Long component, Long capability); /** Called when this filter is deleted. */ public void onRemove(); /** Called to refresh the view. */ public void refreshView(); } /** Binds the view to the presenter. */ public void setPresenter(Presenter presenter); /** Set the title to display for this filter. */ public void setFilterTitle(String title); /** Set the available options for this filter. */ public void setFilterOptionChoices(List<String> filterOptionChoices); /** Set the list of current configuration of this filter: current options filtered on and * to what things are filtered.. */ public void setFilterSettings(List<FilterOption> options, String conjunction, Long attribute, Long component, Long capability); /** Set current list of ACC parts. */ public void setAttributes(Map<String, Long> attributes); public void setComponents(Map<String, Long> components); public void setCapabilities(Map<String, Long> capabilities); /** Makes the widget invisible. */ public void hide(); /** View as a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/FilterView.java
Java
asf20
2,310
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import java.util.List; /** * View for an Attribute widget. * {@See com.google.testing.testify.risk.frontend.model.Attribute} * * @author chrsmith@google.com (Chris Smith) */ public interface AttributeView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * Returns the project ID of the target Component. */ public long getProjectId(); /** * Returns the Attribute ID of the target Attribute. */ public long getAttributeId(); public void updateSignoff(boolean newSignoff); public void onDescriptionEdited(String description); /** * Called when the user renames the given Attribute. */ public void onRename(String newAttributeName); /** * Called when the user deletes the given Attribute. */ public void onRemove(); /** * Called when the user adds a new Label. */ public void onAddLabel(String label); /** * Called when the user updates a Label. */ public void onUpdateLabel(AccLabel label, String newText); /** * Called when the user removes a label. */ public void onRemoveLabel(AccLabel label); /** Updates the view with new attribute data. */ public void refreshView(Attribute attribute); /** Requests the presenter refresh the view's controls. */ public void refreshView(); } /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); public void setDescription(String description); public void setSignedOff(boolean signedOff); /** * Set the UI displaying the Attribute's name. */ public void setAttributeName(String name); /** * Set the UI displaying the Attribute's ID. */ public void setAttributeId(Long id); /** * Set the UI to display the given labels. */ public void setLabels(List<AccLabel> labels); /** * Updates the view to enable editing of attribute data. */ public void enableEditing(); /** * Hides the Widget so it is no longer visible. (Typically after the Attribute has been deleted.) */ public void hide(); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/AttributeView.java
Java
asf20
3,140
// 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.client.view.widgets; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import java.util.Iterator; /** * Customized VerticalPanel for a page. The following CSS classes are exposed by this * widget: * * tty-PageSectionVerticalPanel - The entire panel. * tty-PageSectionVerticalPanelHeader - The header text. * tty-PageSectionVerticalPanelItem - Each item in the panel. * * @author chrsmith@google.com (Chris Smith) */ public class PageSectionVerticalPanel extends Composite implements HasWidgets { private final Label header = new Label(); private final VerticalPanel content = new VerticalPanel(); public PageSectionVerticalPanel() { header.addStyleName("tty-PageSectionVerticalPanelHeader"); content.addStyleName("tty-PageSectionVerticalPanel"); content.add(header); this.initWidget(content); } public void setHeaderText(String newTitle) { header.setText(newTitle); } @Override public void add(Widget w) { w.addStyleName("tty-PageSectionVerticalPanelItem"); content.add(w); } @Override public void clear() { content.clear(); content.add(header); } @Override public Iterator<Widget> iterator() { return content.iterator(); } @Override public boolean remove(Widget w) { return content.remove(w); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/PageSectionVerticalPanel.java
Java
asf20
2,145
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import java.util.Iterator; /** * Organization unit for a navigation pane. * * @author chrsmith@google.com (Chris Smith) */ public class NavSectionPanel extends Composite implements HasWidgets { /** Used to wire parent class to associated UI Binder. */ interface NavSectionPanelUiBinder extends UiBinder<Widget, NavSectionPanel> {} private static final NavSectionPanelUiBinder uiBinder = GWT.create(NavSectionPanelUiBinder.class); @UiField public Label sectionTitle; @UiField public VerticalPanel content; public NavSectionPanel() { initWidget(uiBinder.createAndBindUi(this)); } public String getSectionTitle() { return sectionTitle.getText(); } public void setSectionTitle(String newTitle) { sectionTitle.setText(newTitle); } @Override public void add(Widget w) { content.add(w); } @Override public void clear() { content.clear(); } @Override public Iterator<Widget> iterator() { return content.iterator(); } @Override public boolean remove(Widget w) { return content.remove(w); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/NavSectionPanel.java
Java
asf20
2,129
// 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.client.view.widgets; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.MouseOutEvent; import com.google.gwt.event.dom.client.MouseOutHandler; import com.google.gwt.event.dom.client.MouseOverEvent; import com.google.gwt.event.dom.client.MouseOverHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.Label; 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.Pair; import java.util.Collection; import java.util.List; import java.util.Map; /** * A widget for displaying a set of capabilities in a Grid. * * @author jimr@google.com (Jim Reardon) */ public class CapabilitiesGridWidget extends Composite implements HasValueChangeHandlers<Pair<Component, Attribute>> { private final List<Attribute> attributes = Lists.newArrayList(); private final List<Component> components = Lists.newArrayList(); // Map from intersection key to capability list. private final Multimap<Integer, Capability> capabilityMap = HashMultimap.create(); // Map from intersection key to table cell. private final Map<Integer, HTML> cellMap = Maps.newHashMap(); private final Grid grid = new Grid(); private int highlightedCellRow = -1; private int highlightedCellColumn = -1; public CapabilitiesGridWidget() { grid.addStyleName("tty-ComponentAttributeGrid"); grid.addStyleName("tty-CapabilitiesGrid"); initWidget(grid); } /** * Adds a single capability without clearing out prior capabilities. * * @param capability capability to add. */ public void addCapability(Capability capability) { Integer key = capability.getCapabilityIntersectionKey(); // Add the capability. addCapabilityWithoutUpdate(capability); // Update relevant UI field. updateGridCell(key); } public void deleteCapability(Capability capability) { for (Integer key : capabilityMap.keySet()) { Collection<Capability> c = capabilityMap.get(key); if (c.contains(capability)) { c.remove(capability); updateGridCell(key); } } } public void updateCapability(Capability capability) { deleteCapability(capability); addCapability(capability); } public void setAttributes(List<Attribute> attributes) { this.attributes.clear(); this.attributes.addAll(attributes); redrawGrid(); } public void setComponents(List<Component> components) { this.components.clear(); this.components.addAll(components); redrawGrid(); } public void setCapabilities(List<Capability> capabilities) { capabilityMap.clear(); for (Capability capability : capabilities) { addCapabilityWithoutUpdate(capability); } updateGridCells(); } private void addCapabilityWithoutUpdate(Capability capability) { Integer key = capability.getCapabilityIntersectionKey(); capabilityMap.put(key, capability); } /** * Completely recreates the grid then calls updateGridCells() to update contents of grid. * This should be called if the list of components or attributes changes. */ private void redrawGrid() { grid.clear(); cellMap.clear(); if (components.size() < 1 || attributes.size() < 1) { return; } grid.resize(components.size() + 1, attributes.size() + 1); grid.getCellFormatter().setStyleName(0, 0, "tty-GridXHeaderCell"); // Add component headers. for (int i = 0; i < components.size(); i++) { Label label = new Label(components.get(i).getName()); grid.getCellFormatter().setStyleName(i + 1, 0, "tty-GridXHeaderCell"); grid.setWidget(i + 1, 0, label); } // Add attribute headers. for (int i = 0; i < attributes.size(); i++) { Label label = new Label(attributes.get(i).getName()); grid.getCellFormatter().setStyleName(0, i + 1, "tty-GridYHeaderCell"); grid.setWidget(0, i + 1, label); } // Fill up the rest of the grid with labels. for (int cIndex = 0; cIndex < components.size(); cIndex++) { for (int aIndex = 0; aIndex < attributes.size(); aIndex++) { int row = cIndex + 1; int column = aIndex + 1; Component component = components.get(cIndex); Attribute attribute = attributes.get(aIndex); Integer key = Capability.getCapabilityIntersectionKey(component, attribute); grid.getCellFormatter().setStyleName(row, column, "tty-GridCell"); if (row == highlightedCellRow && column == highlightedCellColumn) { grid.getCellFormatter().addStyleName(row, column, "tty-GridCellSelected"); } HTML cell = new HTML(); cell.addClickHandler(cellClickHandler(row, column)); cell.addMouseOverHandler(createMouseOverHandler(row, column)); cell.addMouseOutHandler(createMouseOutHandler(row, column)); cellMap.put(key, cell); grid.setWidget(row, column, cell); } } updateGridCells(); } /** * Creates a mouse over handler for a specific row and column. * * @param row the row number. * @param column the column number. * @return the mouse over handler. */ private MouseOverHandler createMouseOverHandler(final int row, final int column) { return new MouseOverHandler() { @Override public void onMouseOver(MouseOverEvent event) { mouseOver(row, column); } }; } /** * Generates a mouse out handler for a specific row and column. * * @param row the row. * @param column the column. * @return a mouse out handler. */ private MouseOutHandler createMouseOutHandler(final int row, final int column) { return new MouseOutHandler() { @Override public void onMouseOut(MouseOutEvent event) { mouseOut(row, column); } }; } /** * Handles a mouse out event by removing the formatting on cells that were once highlighted due * to a mouse over event. * * @param row the row that lost mouse over. * @param column the column that lost mouse over. */ private void mouseOut(int row, int column) { CellFormatter formatter = grid.getCellFormatter(); // Remove highlighting from cell. formatter.removeStyleName(row, column, "tty-GridCellHighlighted"); // Remove column highlighting. for (int i = 1; i < grid.getRowCount(); i++) { formatter.removeStyleName(i, column, "tty-GridColumnHighlighted"); } // Remove row highlighting. for (int j = 1; j < grid.getColumnCount(); j++) { formatter.removeStyleName(row, j, "tty-GridRowHighlighted"); } } /** * Handles a mouse over event by highlighting the moused over cell and adding style to the * row and column that is also to be highlighted. * * @param row the row that gained mouse over. * @param column the column that gained mouse over. */ private void mouseOver(int row, int column) { CellFormatter formatter = grid.getCellFormatter(); // Add highlighting to cell. formatter.addStyleName(row, column, "tty-GridCellHighlighted"); // Add column highlighting. for (int i = 1; i < grid.getRowCount(); i++) { if (i != row) { formatter.addStyleName(i, column, "tty-GridColumnHighlighted"); } } // Add row highlighting. for (int j = 1; j < grid.getColumnCount(); j++) { if (j != column) { formatter.addStyleName(row, j, "tty-GridRowHighlighted"); } } } /** * This updates the contents of the grid based off the current capability data. */ private void updateGridCells() { for (Integer key : cellMap.keySet()) { updateGridCell(key); } } private void updateGridCell(Integer key) { int size = capabilityMap.get(key).size(); String text = "&nbsp;"; if (size > 0) { text = Integer.toString(size); } cellMap.get(key).setHTML(text); } private ClickHandler cellClickHandler(final int row, final int column) { final HasValueChangeHandlers<Pair<Component, Attribute>> self = this; return new ClickHandler() { @Override public void onClick(ClickEvent event) { cellClicked(row, column); } }; } private void cellClicked(int row, int column) { final Component component = components.get(row - 1); final Attribute attribute = attributes.get(column - 1); if (highlightedCellRow != -1 && highlightedCellColumn != -1) { grid.getCellFormatter().removeStyleName( highlightedCellRow, highlightedCellColumn, "tty-GridCellSelected"); } grid.getCellFormatter().addStyleName(row, column, "tty-GridCellSelected"); highlightedCellRow = row; highlightedCellColumn = column; ValueChangeEvent.fire(this, new Pair<Component, Attribute>(component, attribute)); } @Override public HandlerRegistration addValueChangeHandler( ValueChangeHandler<Pair<Component, Attribute>> handler) { return addHandler(handler, ValueChangeEvent.getType()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/CapabilitiesGridWidget.java
Java
asf20
10,412
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; /** * Project favorite star. Used to track user favorites. Note that the project favorite star defines * the CSS style tty-ProjectFavoriteStar. * * @author chrsmith@google.com (Chris Smith) */ public class ProjectFavoriteStar extends Composite { private final UserRpcAsync userService; private boolean isStarred = false; private final Image starImage = new Image(); private static final String STAR_ON_URL = "images/star-on.png"; private static final String STAR_OFF_URL = "images/star-off.png"; public ProjectFavoriteStar() { userService = GWT.create(UserRpc.class); starImage.setUrl(STAR_OFF_URL); starImage.addStyleName("tty-ProjectFavoriteStar"); initWidget(starImage); } /** Set's the widget's Starred status. */ public void setStarredStatus(boolean isStarred) { this.isStarred = isStarred; if (isStarred) { starImage.setUrl(STAR_ON_URL); } else { starImage.setUrl(STAR_OFF_URL); } } /** * Attach the current favorite star to the given Project ID. When this widget is clicked, it will * make an RPC call to add the project as a favorite of the user. */ public void attachToProject(final long projectId) { // Add 'click status'. starImage.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent event) { setStarredStatus(!isStarred); if (isStarred) { userService.starProject(projectId, TaCallback.getNoopCallback()); } else { userService.unstarProject(projectId, TaCallback.getNoopCallback()); } } }); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/ProjectFavoriteStar.java
Java
asf20
2,757
// 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.client.view.widgets; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Capability; /** * A widget that displays risk details to the user. No editing is done via this widget, just * informational display. * * @author jimr@google.com (Jim Reardon) */ public class RiskCapabilityWidget extends BaseCapabilityWidget { private final String risk; private Label riskLabel; public RiskCapabilityWidget(Capability capability, String risk) { super(capability); this.risk = risk; updateRiskLabel(); } @Override public void makeEditable() { // Always disable editing, no matter what. This is not a widget for editing, but for viewing. } private void updateRiskLabel() { riskLabel.setText("Risk: " + risk); } @UiFactory @Override public EasyDisclosurePanel createDisclosurePanel() { HorizontalPanel header = new HorizontalPanel(); header.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); header.setStyleName("tty-CapabilityRiskHeader"); header.add(capabilityLabel); riskLabel = new Label(); riskLabel.setStyleName("tty-CapabilityRiskValueHeader"); updateRiskLabel(); header.add(riskLabel); EasyDisclosurePanel panel = new EasyDisclosurePanel(header); panel.setOpen(false); return panel; } public void setRiskContent(Widget content) { disclosureContent.setWidget(content); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/RiskCapabilityWidget.java
Java
asf20
2,303
// 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.client.view.widgets; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.TextBox; /** * Widget for a DataRequest parameter with an arbitrary parameter key. * * @author chrsmith@google.com (Chris Smith) */ public class CustomParameterWidget extends Composite implements DataRequestParameterWidget { private final TextBox keyTextBox = new TextBox(); private final TextBox valueTextBox = new TextBox(); private boolean isDeleted = false; private final Image removeParameterImage = new Image("/images/x.png"); public CustomParameterWidget(String key, String value) { HorizontalPanel panel = new HorizontalPanel(); panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); panel.addStyleName("tty-DataRequestParameter"); panel.add(keyTextBox); panel.add(valueTextBox); panel.add(removeParameterImage); removeParameterImage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { isDeleted = true; fireChangeEvent(); } }); initWidget(panel); } private void fireChangeEvent() { NativeEvent event = Document.get().createChangeEvent(); ChangeEvent.fireNativeEvent(event, this); } @Override public String getParameterKey() { if (isDeleted) { return null; } return keyTextBox.getText(); } @Override public String getParameterValue() { if (isDeleted) { return null; } return valueTextBox.getText(); } @Override public HandlerRegistration addChangeHandler(ChangeHandler handler) { return addHandler(handler, ChangeEvent.getType()); } @Override public boolean isDeleted() { return isDeleted; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/CustomParameterWidget.java
Java
asf20
2,909
// 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.client.view.widgets; import com.google.gwt.event.dom.client.HasChangeHandlers; import com.google.gwt.user.client.ui.Widget; /** * Base interface visualizing a parameter to a data request. * * @author chrsmith@google.com (Chris Smith) */ public interface DataRequestParameterWidget extends HasChangeHandlers { public String getParameterKey(); public String getParameterValue(); public Widget asWidget(); public boolean isDeleted(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/DataRequestParameterWidget.java
Java
asf20
1,107
// 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.client.view.widgets; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; 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.FailureRate; import com.google.testing.testify.risk.frontend.model.UserImpact; import java.util.Collection; import java.util.List; /** * A capability widget that allows you to edit the details of the capability. Hook up * an update and delete listener to be notified of edits on this widget. * * @author jimr@google.com (Jim Reardon) */ public class EditCapabilityWidget extends Composite implements HasValue<Capability> { interface EditCapabilityWidgetUiBinder extends UiBinder<Widget, EditCapabilityWidget> {} private static final EditCapabilityWidgetUiBinder uiBinder = GWT.create(EditCapabilityWidgetUiBinder.class); private Capability capability; private final List<Attribute> attributes = Lists.newArrayList(); private final List<Component> components = Lists.newArrayList(); @UiField protected FlowPanel labelsPanel; @UiField protected HorizontalPanel failurePanel; @UiField protected HorizontalPanel impactPanel; @UiField protected ListBox attributeBox; @UiField protected ListBox componentBox; @UiField protected TextBox capabilityName; @UiField protected TextArea description; @UiField protected Label capabilityGripper; @UiField protected HorizontalPanel buttonPanel; @UiField public HorizontalPanel savedPanel; @UiField protected EasyDisclosurePanel disclosurePanel; @UiField protected Button cancelButton; @UiField protected Button saveButton; @UiField protected Image deleteImage; @UiField protected Label capabilityId; private final Label capabilityLabel = new Label(); private LabelWidget addNewLabel; private Collection<String> labelSuggestions = Lists.newArrayList(); private boolean isEditable = false; private boolean isDeletable = true; /** * Creates a widget which exposes the ability to edit the widget. * * @param capability the capability for this widget. */ public EditCapabilityWidget(Capability capability) { this.capability = capability; initWidget(uiBinder.createAndBindUi(this)); capabilityLabel.setText(capability.getName()); description.getElement().setAttribute("placeholder", "Enter description of this capability..."); refresh(); } public Widget getCapabilityGripper() { return capabilityGripper; } public void expand() { disclosurePanel.setOpen(true); } public void setAttributes(List<Attribute> attributes) { this.attributes.clear(); this.attributes.addAll(attributes); refresh(); } public void setComponents(List<Component> components) { this.components.clear(); this.components.addAll(components); refresh(); } public long getCapabilityId() { return capability.getCapabilityId(); } public void disableDelete() { isDeletable = false; deleteImage.setVisible(false); } @UiFactory public EasyDisclosurePanel createDisclosurePanel() { EasyDisclosurePanel panel = new EasyDisclosurePanel(capabilityLabel); panel.setOpen(false); return panel; } @UiHandler("deleteImage") protected void handleDelete(ClickEvent event) { String promptText = "Are you sure you want to remove " + capability.getName() + "?"; if (Window.confirm(promptText)) { setValue(null, true); } } @UiHandler("cancelButton") protected void handleCancel(ClickEvent event) { refresh(); } @UiHandler("saveButton") public void handleSave(ClickEvent event) { savedPanel.setVisible(false); long selectedAttribute; long selectedComponent; try { selectedAttribute = Long.parseLong(attributeBox.getValue(attributeBox.getSelectedIndex())); selectedComponent = Long.parseLong(componentBox.getValue(componentBox.getSelectedIndex())); } catch (NumberFormatException e) { NotificationUtil.displayErrorMessage("Couldn't save capability. The attribute or" + " component ID was invalid."); return; } // Handle updates. capability.setName(capabilityName.getValue()); capability.setDescription(description.getValue()); capability.setFailureRate( FailureRate.fromDescription(getSelectedOptionInPanel(failurePanel))); capability.setUserImpact( UserImpact.fromDescription(getSelectedOptionInPanel(impactPanel))); capability.setAttributeId(selectedAttribute); capability.setComponentId(selectedComponent); if ((capability.getComponentId() != selectedComponent) || (capability.getAttributeId() != selectedAttribute)) { Window.alert("The capability " + capability.getName() + " will disappear from the " + " currently visible list because you have changed its attribute or component."); } // Tell the world that we've updated this capability. ValueChangeEvent.fire(this, capability); } public void showSaved() { // Show saved message. savedPanel.setVisible(true); Timer timer = new Timer() { @Override public void run() { savedPanel.setVisible(false); } }; // Make the saved text disappear after 10 seconds. timer.schedule(5000); } /** * Updates the label suggestions for all labels on this view. */ public void setLabelSuggestions(Collection<String> labelSuggestions) { this.labelSuggestions.clear(); this.labelSuggestions.addAll(labelSuggestions); for (Widget w : labelsPanel) { if (w instanceof LabelWidget) { LabelWidget l = (LabelWidget) w; l.setLabelSuggestions(this.labelSuggestions); } } } private void refresh() { capabilityLabel.setText(capability.getName()); capabilityName.setText(capability.getName()); createLabelsPanel(); description.setText(capability.getDescription()); createFailureBox(); createImpactBox(); createAttributeBox(); createComponentBox(); capabilityName.setEnabled(isEditable); capabilityGripper.setVisible(isEditable); description.setEnabled(isEditable); enableOrDisableAllRadioButtons(failurePanel, isEditable); enableOrDisableAllRadioButtons(impactPanel, isEditable); attributeBox.setEnabled(isEditable); componentBox.setEnabled(isEditable); buttonPanel.setVisible(isEditable); } private void createLabelsPanel() { labelsPanel.clear(); for (AccLabel label : capability.getAccLabels()) { createLabel(label); } addBlankLabel(); } private void createLabel(final AccLabel label) { final LabelWidget widget = new LabelWidget(label.getLabelText()); widget.setLabelSuggestions(labelSuggestions); widget.setEditable(isEditable); widget.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { if (event.getValue() == null) { labelsPanel.remove(widget); capability.removeLabel(label); } else { label.setLabelText(event.getValue()); } } }); labelsPanel.add(widget); } private void addBlankLabel() { final String newText = "new label"; addNewLabel = new LabelWidget(newText, true); addNewLabel.setLabelSuggestions(labelSuggestions); addNewLabel.setEditable(true); addNewLabel.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { labelsPanel.remove(addNewLabel); AccLabel label = capability.addLabel(event.getValue()); createLabel(label); addBlankLabel(); } }); addNewLabel.setVisible(isEditable); labelsPanel.add(addNewLabel); } private void createFailureBox() { failurePanel.clear(); RadioButton button; for (FailureRate rate : FailureRate.values()) { button = new RadioButton("failure" + capability.getCapabilityId().toString(), rate.getDescription()); failurePanel.add(button); if (rate.equals(capability.getFailureRate())) { button.setValue(true); } } } private void createImpactBox() { impactPanel.clear(); RadioButton button; for (UserImpact impact : UserImpact.values()) { button = new RadioButton("impact" + capability.getCapabilityId().toString(), impact.getDescription()); impactPanel.add(button); if (impact.equals(capability.getUserImpact())) { button.setValue(true); } } } private void enableOrDisableAllRadioButtons(Panel panel, boolean enable) { for (Widget w : panel) { if (w instanceof RadioButton) { RadioButton b = (RadioButton) w; b.setEnabled(enable); } } } private String getSelectedOptionInPanel(Panel panel) { for (Widget w : panel) { if (w instanceof RadioButton) { RadioButton b = (RadioButton) w; if (b.getValue()) { return b.getText(); } } } return null; } private void createAttributeBox() { attributeBox.clear(); int i = 0; for (Attribute attribute : attributes) { attributeBox.addItem(attribute.getName(), attribute.getAttributeId().toString()); if (attribute.getAttributeId() == capability.getAttributeId()) { attributeBox.setSelectedIndex(i); } i++; } } private void createComponentBox() { componentBox.clear(); int i = 0; for (Component component : components) { componentBox.addItem(component.getName(), component.getComponentId().toString()); if (component.getComponentId() == capability.getComponentId()) { componentBox.setSelectedIndex(i); } i++; } } public void makeEditable() { isEditable = true; deleteImage.setVisible(isDeletable); enableOrDisableAllRadioButtons(failurePanel, true); enableOrDisableAllRadioButtons(impactPanel, true); description.setEnabled(true); attributeBox.setEnabled(true); componentBox.setEnabled(true); capabilityName.setEnabled(true); capabilityGripper.setVisible(true); buttonPanel.setVisible(true); for (Widget widget : labelsPanel) { LabelWidget label = (LabelWidget) widget; label.setEditable(true); } addNewLabel.setVisible(true); } @Override public Capability getValue() { return capability; } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Capability> handler) { return addHandler(handler, ValueChangeEvent.getType()); } @Override public void setValue(Capability capability) { this.capability = capability; } @Override public void setValue(Capability capability, boolean fireEvents) { this.capability = capability; if (fireEvents) { ValueChangeEvent.fire(this, capability); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/EditCapabilityWidget.java
Java
asf20
13,040
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaApplication; import com.google.testing.testify.risk.frontend.model.Capability; /** * Displays a Capability which, upon click, takes a user to another page. * * @author jimr@google.com (Jim Reardon) */ public class LinkCapabilityWidget extends Composite { interface CapabilityWidgetBinder extends UiBinder<Widget, LinkCapabilityWidget> { } private static final CapabilityWidgetBinder uiBinder = GWT.create(CapabilityWidgetBinder.class); @UiField public Label capabilityId; @UiField public Label capabilityLabel; private final Capability capability; /** * @param capability */ public LinkCapabilityWidget(Capability capability) { initWidget(uiBinder.createAndBindUi(this)); this.capability = capability; initializeWidget(); } private void initializeWidget() { capabilityLabel.setText(capability.getName()); capabilityId.setText(Long.toString(capability.getCapabilityId())); capabilityLabel.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { History.newItem("/" + capability.getParentProjectId() + "/" + TaApplication.PAGE_HISTORY_TOKEN_CAPABILITY_DETAILS + "/" + capability.getCapabilityId()); } }); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/LinkCapabilityWidget.java
Java
asf20
2,414
// 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.client.view.widgets; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import java.util.List; /** * Widget a constrained DataRequest parameter, where the key values are fixed. * * @author chrsmith@google.com (Chris Smith) */ public class ConstrainedParameterWidget extends Composite implements DataRequestParameterWidget { private final ListBox keyListBox = new ListBox(); private final TextBox valueTextBox = new TextBox(); private boolean isDeleted = false; private final Image removeParameterImage = new Image("/images/x.png"); public ConstrainedParameterWidget(List<String> keyValues, String key, String value) { keyListBox.clear(); for (String keyValue : keyValues) { keyListBox.addItem(keyValue); } int startingKeyIndex = -1; if (keyValues.contains(key)) { startingKeyIndex = keyValues.indexOf(key); } else { // Initialized with a key not in the key values? Likely a bug somewhere... startingKeyIndex = 0; } keyListBox.setSelectedIndex(startingKeyIndex); valueTextBox.setText(value); final HasHandlers self = this; removeParameterImage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { isDeleted = true; fireChangeEvent(); } }); HorizontalPanel panel = new HorizontalPanel(); panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); panel.addStyleName("tty-DataRequestParameter"); panel.add(keyListBox); panel.add(valueTextBox); panel.add(removeParameterImage); initWidget(panel); } private void fireChangeEvent() { NativeEvent event = Document.get().createChangeEvent(); ChangeEvent.fireNativeEvent(event, this); } @Override public String getParameterKey() { if (isDeleted) { return null; } int selectedIndex = keyListBox.getSelectedIndex(); return keyListBox.getItemText(selectedIndex); } @Override public String getParameterValue() { if (isDeleted) { return null; } return valueTextBox.getText(); } @Override public boolean isDeleted() { return isDeleted; } @Override public HandlerRegistration addChangeHandler(ChangeHandler handler) { return addHandler(handler, ChangeEvent.getType()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/ConstrainedParameterWidget.java
Java
asf20
3,609
// 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.client.view.widgets; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.HasWidgetsReorderedHandler; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedEvent; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedHandler; import com.allen_sauer.gwt.dnd.client.DragEndEvent; import com.allen_sauer.gwt.dnd.client.DragHandler; import com.allen_sauer.gwt.dnd.client.DragStartEvent; import com.allen_sauer.gwt.dnd.client.PickupDragController; import com.allen_sauer.gwt.dnd.client.drop.VerticalPanelDropController; import java.util.Iterator; import java.util.List; /** * A VerticalPanel which supports reordering via drag and drop. * * @param <T> Type of the widget to display on the panel. * @author chrsmith@google.com (Chris Smith) */ public class SortableVerticalPanel<T extends Widget> extends Composite implements HasWidgetsReorderedHandler, Iterable<Widget> { private final SimplePanel content = new SimplePanel(); private VerticalPanel currentVerticalPanel = new VerticalPanel(); public SortableVerticalPanel() { initWidget(content); } /** * Clears the vertical panel and adds the list of widgets. The provided function will be used to * get the widget's drag target (such as header text or a gripper image). * * @param widgets the list of widgets to display on the generated panel. * @param getDragTarget function for getting the 'dragable area' of any given widget. (Such as * a gripping area or header label. */ public void setWidgets(List<T> widgets, Function<T, Widget> getDragTarget) { AbsolutePanel boundaryPanel = new AbsolutePanel(); boundaryPanel.setSize("100%", "100%"); boundaryPanel.clear(); content.clear(); content.add(boundaryPanel); // The VerticalPanel which actually holds the list of widgets. currentVerticalPanel = new VerticalPanel(); // The VerticalPanelDropController handles DOM manipulation. final VerticalPanelDropController widgetDropController = new VerticalPanelDropController(currentVerticalPanel); boundaryPanel.add(currentVerticalPanel); DragHandler dragHandler = createDragHandler(currentVerticalPanel); PickupDragController widgetDragController = new PickupDragController(boundaryPanel, false); widgetDragController.setBehaviorMultipleSelection(false); widgetDragController.addDragHandler(dragHandler); widgetDragController.registerDropController(widgetDropController); // Add each widget to the VerticalPanel and enable dragging via its DragTarget. for (T widget : widgets) { currentVerticalPanel.add(widget); widgetDragController.makeDraggable(widget, getDragTarget.apply(widget)); } } /** * Returns the number of Widgets on the VerticalPanel. */ public int getWidgetCount() { return currentVerticalPanel.getWidgetCount(); } /** * Returns the Widget at the specified index. */ public Widget getWidget(int index) { return currentVerticalPanel.getWidget(index); } /** * Returns a generic DragHandler for notification of drag events. */ private DragHandler createDragHandler(final VerticalPanel verticalPanel) { // TODO(chrsmith): Provide a way to hook into events. (Required to preserve ordering.) return new DragHandler() { @Override public void onDragEnd(DragEndEvent event) { List<Widget> widgetList = Lists.newArrayList(); for (int index = 0; index < verticalPanel.getWidgetCount(); index++) { widgetList.add(verticalPanel.getWidget(index)); } fireEvent(new WidgetsReorderedEvent(widgetList)); } @Override public void onDragStart(DragStartEvent event) {} @Override public void onPreviewDragEnd(DragEndEvent event) {} @Override public void onPreviewDragStart(DragStartEvent event) {} }; } @Override public HandlerRegistration addWidgetsReorderedHandler(WidgetsReorderedHandler handler) { return super.addHandler(handler, WidgetsReorderedEvent.getType()); } @Override public Iterator<Widget> iterator() { return currentVerticalPanel.iterator(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/SortableVerticalPanel.java
Java
asf20
5,243
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Capability; /** * Base display for a capability. This widget is intended to be extended to supply content * in the disclosure panel depending on view (for example, on the Capabilities page, the ability * to edit capability details would be contained there. On a risk page, details on the risk * assessment would be contained there. And so on). * * @author jimr@google.com (Jim Reardon) */ public class BaseCapabilityWidget extends Composite implements HasValueChangeHandlers<Capability> { interface CapabilityWidgetBinder extends UiBinder<Widget, BaseCapabilityWidget> { } private static final CapabilityWidgetBinder uiBinder = GWT.create(CapabilityWidgetBinder.class); @UiField public Image capabilityGripper; @UiField public EasyDisclosurePanel disclosurePanel; @UiField public SimplePanel disclosureContent; @UiField public Label capabilityId; @UiField public Image deleteCapabilityImage; protected final Label capabilityLabel = new Label(); protected final Capability capability; // If this widget allows editing. protected boolean isEditable = false; public BaseCapabilityWidget(Capability capability) { initWidget(uiBinder.createAndBindUi(this)); this.capability = capability; initializeWidget(); } @UiFactory public EasyDisclosurePanel createDisclosurePanel() { EasyDisclosurePanel panel = new EasyDisclosurePanel(capabilityLabel); panel.setOpen(false); return panel; } private void initializeWidget() { capabilityLabel.setStyleName("tty-CapabilityName"); deleteCapabilityImage.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { ValueChangeEvent.fire(BaseCapabilityWidget.this, null); } }); capabilityLabel.setText(capability.getName()); capabilityId.setText(Long.toString(capability.getCapabilityId())); } public void makeEditable() { isEditable = true; capabilityGripper.setVisible(true); deleteCapabilityImage.setVisible(true); } @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Capability> handler) { return addHandler(handler, ValueChangeEvent.getType()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/BaseCapabilityWidget.java
Java
asf20
3,706
// 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.client.view.widgets; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DeckPanel; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.MultiWordSuggestOracle; import com.google.gwt.user.client.ui.SuggestBox; import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay; import java.util.Collection; /** * Displays a label with a little delete X as well. You can click the X to delete the label. * * @author jimr@google.com (Jim Reardon) */ public class LabelWidget extends Composite implements HasValue<String>, HasValueChangeHandlers<String> { private HorizontalPanel contentPanel = new HorizontalPanel(); private Image image = new Image(); // The deck panel will have to entries -- the view mode, and the edit mode. DeckPanel will // only make one visible at a time. private DeckPanel deckPanel = new DeckPanel(); private MultiWordSuggestOracle oracle = new MultiWordSuggestOracle(" -"); private SuggestBox inputBox = new SuggestBox(oracle); private Label label = new Label(); private static final int VIEW_MODE = 0; private static final int EDIT_MODE = 1; private boolean canEdit = false; public LabelWidget(String text) { this(text, false); } /** * Constructs a label for a given object, allowing customized styling. The constructed * label will use styles: * tty-GenericLabel * tty-GenericLabelRemoveLabelImage * @param text the textual representation for this label. * @param isAddWidget true if this is a "new label..." widget, false if not. */ public LabelWidget(String text, final boolean isAddWidget) { DefaultSuggestionDisplay suggestionDisplay = (DefaultSuggestionDisplay) inputBox.getSuggestionDisplay(); suggestionDisplay.setPopupStyleName("tty-SuggestBoxPopup"); contentPanel.addStyleName("tty-RemovableLabel"); if (isAddWidget) { // Craft a little plus image. image.setStyleName("tty-RemovableLabelAddImage"); image.setUrl("images/collapsed_12.png"); image.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { switchMode(EDIT_MODE); } }); contentPanel.add(image); } // Craft the view mode. label.setText(text); label.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent arg0) { switchMode(EDIT_MODE); } }); deckPanel.add(label); // Craft the edit mode. if (!isAddWidget) { inputBox.setText(text); } inputBox.getTextBox().addBlurHandler(new BlurHandler() { @Override public void onBlur(BlurEvent arg0) { switchMode(VIEW_MODE); } }); inputBox.getTextBox().addKeyDownHandler(new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { switchMode(VIEW_MODE); } else if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) { if (isAddWidget) { inputBox.setText(""); } else { inputBox.setText(label.getText()); } switchMode(VIEW_MODE); } } }); // Explicitly does not call switchMode to avoid logic inside that function that would think // we have switched from edit mode to view mode. deckPanel.showWidget(VIEW_MODE); deckPanel.add(inputBox); contentPanel.add(deckPanel); if (!isAddWidget) { // Craft the delete button. image.setStyleName("tty-RemovableLabelDeleteImage"); image.setUrl("images/x.png"); image.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { setValue(null, true); } }); contentPanel.add(image); } // Set some alignments to make the widget pretty. contentPanel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE); contentPanel.setCellVerticalAlignment(image, HasVerticalAlignment.ALIGN_MIDDLE); initWidget(contentPanel); } private void switchMode(int mode) { // Just keep them in view mode if they can't edit this widget. if (!canEdit) { deckPanel.showWidget(VIEW_MODE); return; } if (mode == VIEW_MODE) { String text = inputBox.getText(); if (!text.equals(label.getText())) { // Don't save an empty label. if (!"".equals(text)) { // We have updates to save. setValue(inputBox.getText(), true); } } } int width = label.getOffsetWidth(); deckPanel.showWidget(mode); if (mode == EDIT_MODE) { inputBox.setWidth(String.valueOf(String.valueOf(width)) + "px"); inputBox.setFocus(true); } } public void setEditable(boolean canEdit) { this.canEdit = canEdit; image.setVisible(canEdit); } /** * Sets the list of suggestions for the autocomplete box. * @param suggestions list of items to suggest off of. */ public void setLabelSuggestions(Collection<String> suggestions) { oracle.clear(); oracle.addAll(suggestions); } @Override public String getValue() { return label.getText(); } @Override public void setValue(String value) { setValue(value, false); } @Override public void setValue(String value, boolean fireEvents) { String old = label.getText(); label.setText(value); inputBox.setText(value); if (fireEvents) { ValueChangeEvent.fireIfNotEqual(this, old, value); } } /** * Will fire when value of text changes or delete is clicked (the value will be null if deleted). */ @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return addHandler(handler, ValueChangeEvent.getType()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/LabelWidget.java
Java
asf20
7,391
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent; import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent.DialogResult; import com.google.testing.testify.risk.frontend.client.event.DialogClosedHandler; import com.google.testing.testify.risk.frontend.client.event.HasDialogClosedHandler; /** * Standard dialog box with OK/Cancel buttons. * * @author chrsmith@google.com (Chris Smith) */ public class StandardDialogBox extends Composite implements HasDialogClosedHandler { interface StandardDialogBoxUiBinder extends UiBinder<Widget, StandardDialogBox> {} private static final StandardDialogBoxUiBinder uiBinder = GWT.create(StandardDialogBoxUiBinder.class); @UiField protected VerticalPanel dialogContent; @UiField protected Button okButton; @UiField protected Button cancelButton; /** If this is displayed, get a handle to the owning dialog box. */ private DialogBox dialogBox; public StandardDialogBox() { initWidget(uiBinder.createAndBindUi(this)); } /** * @return the dialog's content. Consumers will add any custom widgets to the returned Panel. */ public Panel getDialogContent() { return dialogContent; } /** * Displays the Dialog. */ public static void showAsDialog(StandardDialogBox dialogWidget) { DialogBox dialogBox = new DialogBox(); dialogWidget.dialogBox = dialogBox; dialogBox.addStyleName("tty-StandardDialogBox"); dialogBox.setText(dialogWidget.getTitle()); dialogBox.add(dialogWidget); dialogBox.center(); dialogBox.show(); } /** * Gets called whenever the OK Button is clicked. */ @UiHandler("okButton") public void handleOkButtonClicked(ClickEvent event) { if (dialogBox != null) { dialogBox.hide(); } fireEvent(new DialogClosedEvent(DialogResult.OK)); } /** * Gets called whenever the Cancel Button is clicked. */ @UiHandler("cancelButton") public void handleCancelButtonClicked(ClickEvent event) { if (dialogBox != null) { dialogBox.hide(); } fireEvent(new DialogClosedEvent(DialogResult.Cancel)); } @Override public HandlerRegistration addDialogClosedHandler(DialogClosedHandler handler) { return super.addHandler(handler, DialogClosedEvent.getType()); } public void add(Widget w) { dialogContent.add(w); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/StandardDialogBox.java
Java
asf20
3,628
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window.Location; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; /** * Header widget for all pages, containing the logo, login information, and so on. * * @author chrsmith@google.com (Chris Smith) */ public class PageHeaderWidget extends Composite { interface PageHeaderWidgetUiBinder extends UiBinder<Widget, PageHeaderWidget> {} private static final PageHeaderWidgetUiBinder uiBinder = GWT.create(PageHeaderWidgetUiBinder.class); @UiField protected Label userEmailAddress; @UiField protected Label userEmailAddressDivider; @UiField protected Anchor signInOrOutLink; @UiField protected Anchor feedbackLink; private final UserRpcAsync userService; /** * Constructs a PageHeaderWidget instance. */ public PageHeaderWidget(UserRpcAsync userService) { initWidget(uiBinder.createAndBindUi(this)); this.userService = userService; initializeLoginBar(); } @UiHandler("feedbackLink") protected void onFeedbackClick(ClickEvent event) { startFeedback(); } private static native void startFeedback() /*-{ $wnd.userfeedback.api.startFeedback({ productId : 69289 }); }-*/; /** * Initializes the login bar with the current user's email address if applicable. */ private void initializeLoginBar() { String returnUrl = Location.getHref(); userService.getLoginStatus(returnUrl, new TaCallback<LoginStatus>("Querying Login Status") { @Override public void onSuccess(LoginStatus result) { refreshView(result); } }); } /** * Refreshes UI elements based on the user's current login status. */ public void refreshView(LoginStatus status) { userEmailAddress.setText(status.getEmail()); signInOrOutLink.setHref(status.getUrl()); if (status.getIsLoggedIn()) { userEmailAddressDivider.setVisible(true); signInOrOutLink.setText("Sign out"); } else { userEmailAddressDivider.setVisible(false); signInOrOutLink.setText("Sign in"); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/PageHeaderWidget.java
Java
asf20
3,320
// 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.client.view.widgets; import com.google.gwt.event.logical.shared.CloseEvent; import com.google.gwt.event.logical.shared.CloseHandler; import com.google.gwt.event.logical.shared.OpenEvent; import com.google.gwt.event.logical.shared.OpenHandler; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DisclosurePanel; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HasWidgets; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; import java.util.Iterator; /** * A disclosure panel that automatically switches the headers between a closed header and * an open header for you. * * @author jimr@google.com (Jim Reardon) */ public class EasyDisclosurePanel extends Composite implements HasWidgets { private final DisclosurePanel panel = new DisclosurePanel(); private final Widget openedHeader; private final Widget closedHeader; private final HorizontalPanel header = new HorizontalPanel(); private final Image expandedImage = new Image("images/expanded_12.png"); private final Image collapsedImage = new Image("images/collapsed_12.png"); /** * Constructs an Easy Disclosure Panel with the same widget for the closed / opened * header. Easy Disclosure Panel will automatically change the expanded/collapsed * image. * * @param header widget to display along side the +/- zippy. */ public EasyDisclosurePanel(Widget header) { this(header, null); } public EasyDisclosurePanel(Widget openedHeader, Widget closedHeader) { this.openedHeader = openedHeader; this.closedHeader = closedHeader; header.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); header.setStyleName("tty-DisclosurePanelHeader"); setHeaderOpened(); panel.setAnimationEnabled(true); panel.addStyleName("tty-DisclosurePanel"); panel.setOpen(true); panel.setHeader(header); panel.addCloseHandler(new CloseHandler<DisclosurePanel>() { @Override public void onClose(CloseEvent<DisclosurePanel> event) { setHeaderClosed(); } }); panel.addOpenHandler(new OpenHandler<DisclosurePanel>() { @Override public void onOpen(OpenEvent<DisclosurePanel> event) { setHeaderOpened(); } }); initWidget(panel); } private void setHeaderClosed() { header.clear(); header.add(collapsedImage); header.setCellWidth(collapsedImage, "20px"); header.add(closedHeader != null ? closedHeader : openedHeader); } private void setHeaderOpened() { header.clear(); header.add(expandedImage); header.setCellWidth(expandedImage, "20px"); header.add(openedHeader); } public void setOpen(boolean open) { panel.setOpen(open); } @Override public void add(Widget w) { panel.add(w); } @Override public void clear() { panel.clear(); } @Override public Iterator<Widget> iterator() { return panel.iterator(); } @Override public boolean remove(Widget w) { return panel.remove(w); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/EasyDisclosurePanel.java
Java
asf20
3,793
// 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.client.view.widgets; import com.google.common.base.Function; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DeckPanel; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.Hyperlink; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.testing.testify.risk.frontend.client.presenter.TaPagePresenter; /** * Navigation link widget. This control is a wrapper on top of a GWT Hyperlink widget, * except that it enables you to disable the control as well as associate the link's target history * token with a given project. * <p> * The widget has three CSS properties: * tty-NavigationLink, which covers the entire widget. * tty-NavigationLinkText, which covers just the link text (even the disabled text). * tty-NavigationLinkTextDisabled, which covers the text when disabled. * * @author jimr@google.com (Jim Reardon) */ public class NavigationLink extends Composite implements HasText { private final DeckPanel panel; // The hyper link is displayed when the control is enabled; otherwise the fake link will be. private final Label fakeLink; private final Hyperlink realLink; private long projectId; private String targetHistoryToken; private TaPagePresenter presenter; private Function<Void, TaPagePresenter> createPresenterFunction; private static final int WIDGET_ID_ENABLED = 0; private static final int WIDGET_ID_DISABLED = 1; private static final String NAV_STYLE_UNSELECTED = "tty-LeftNavItem"; private static final String NAV_STYLE_SELECTED = "tty-LeftNavItemSelected"; private static final String NAV_STYLE_DISABLED = "tty-LeftNavItemDisabled"; public NavigationLink() { this("", -1, "", null); } public NavigationLink(String text, long projectId, String targetHistoryToken, Function<Void, TaPagePresenter> createPresenterFunction) { this.targetHistoryToken = targetHistoryToken; this.projectId = projectId; this.createPresenterFunction = createPresenterFunction; panel = new DeckPanel(); SimplePanel fakeLinkPanel = new SimplePanel(); fakeLink = new Label(text); fakeLinkPanel.add(fakeLink); realLink = new Hyperlink(text, getHyperlinkTarget()); panel.add(realLink); panel.add(fakeLinkPanel); enable(); super.initWidget(panel); } public void setCreatePresenterFunction(Function<Void, TaPagePresenter> function) { this.createPresenterFunction = function; } public TaPagePresenter getPresenter() { if (presenter == null) { presenter = createPresenterFunction.apply(null); } return presenter; } @Override public void setText(String text) { fakeLink.setText(text); realLink.setText(text); } @Override public String getText() { return realLink.getText(); } public void setProjectId(long projectId) { this.projectId = projectId; realLink.setTargetHistoryToken(getHyperlinkTarget()); } public void setTargetHistoryToken(String token) { this.targetHistoryToken = token; realLink.setTargetHistoryToken(getHyperlinkTarget()); } public String getHistoryTokenName() { return targetHistoryToken; } /** Updates the hyperlink's target to encode project name and history token. */ private String getHyperlinkTarget() { return "/" + projectId + "/" + targetHistoryToken; } public Hyperlink getHyperlink() { return realLink; } public void enable() { panel.setStyleName(NAV_STYLE_UNSELECTED); panel.showWidget(WIDGET_ID_ENABLED); } public void select() { panel.setStyleName(NAV_STYLE_SELECTED); panel.showWidget(WIDGET_ID_ENABLED); } public void unSelect() { enable(); } public void disable() { panel.setStyleName(NAV_STYLE_DISABLED); panel.showWidget(WIDGET_ID_DISABLED); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/NavigationLink.java
Java
asf20
4,525
// 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.client.view.widgets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.BlurEvent; import com.google.gwt.event.dom.client.BlurHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.FocusEvent; import com.google.gwt.event.dom.client.FocusHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.dom.client.KeyDownHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DeckPanel; import com.google.gwt.user.client.ui.FocusPanel; import com.google.gwt.user.client.ui.HasText; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; /** * Label which turns into an editable TextArea widget on click. * * @author chrsmith@google.com (Chris Smith) */ public class EditableLabel extends Composite implements HasText, HasValue<String> { interface EditableLabelUiBinder extends UiBinder<Widget, EditableLabel> {} private static final EditableLabelUiBinder uiBinder = GWT.create(EditableLabelUiBinder.class); @UiField public Label label; @UiField public TextBox textArea; @UiField public DeckPanel deckPanel; @UiField public FocusPanel focusPanel; private static final int LABEL_INDEX = 0; private static final int TEXTAREA_INDEX = 1; private boolean isReadOnly = false; public EditableLabel() { initWidget(uiBinder.createAndBindUi(this)); deckPanel.showWidget(LABEL_INDEX); // When we receive focus, switch to edit mode. focusPanel.addFocusHandler( new FocusHandler() { @Override public void onFocus(FocusEvent event) { switchToEdit(); } }); // When the label is clicked, switch to edit mode. label.addClickHandler( new ClickHandler() { @Override public void onClick(ClickEvent event) { switchToEdit(); } }); // When focus leaves the text area, switch to display/readonly mode. textArea.addBlurHandler( new BlurHandler() { @Override public void onBlur(BlurEvent event) { switchToLabel(); } }); // On key Enter, commit the text and fire a change event. // On key Down, revert the text if the user presses escape. textArea.addKeyDownHandler( new KeyDownHandler() { @Override public void onKeyDown(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { switchToLabel(); } else if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) { textArea.setText(label.getText()); switchToLabel(); } } }); } /** * Sets the widget's ReadOnly flag, which prevents editing. */ public void setReadOnly(boolean isReadOnly) { this.isReadOnly = isReadOnly; deckPanel.showWidget(0); } /** Switches the widget into 'Edit' mode. */ public void switchToEdit() { if (isReadOnly || deckPanel.getVisibleWidget() == TEXTAREA_INDEX) { return; } textArea.setText(getValue()); deckPanel.showWidget(TEXTAREA_INDEX); textArea.setFocus(true); } /** Switches the widget into 'Readonly' mode. */ public void switchToLabel() { if (deckPanel.getVisibleWidget() == LABEL_INDEX) { return; } // Fires the ValueChanged event. setValue(textArea.getText(), true); deckPanel.showWidget(LABEL_INDEX); } // Implementation of HasValue<String>, which adds notification of text changed events. @Override public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) { return addHandler(handler, ValueChangeEvent.getType()); } @Override public String getValue() { return getText(); } @Override public void setValue(String value) { setText(value); } @Override public void setValue(String value, boolean fireEvents) { // Set the value before we fire the event, so that consumers can normalize the text in any event // handlers. String startingValue = getValue(); setValue(value); if (fireEvents) { ValueChangeEvent.fireIfNotEqual(this, startingValue, value); } } // Implementation of HasText, enabling you to set the default text when used in a UIBinder. @Override public void setText(String text) { label.setText(text); textArea.setText(text); } @Override public String getText() { return label.getText(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/widgets/EditableLabel.java
Java
asf20
5,651
// 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.client.view; import com.google.gwt.user.client.ui.Widget; 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 java.util.Collection; import java.util.List; /** * View on top of any user interface for visualizing Capabilities. * * @author chrsmith@google.com (Chris Smith) */ public interface CapabilitiesView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * Notify the Presenter that a new Capability has been added. */ public void onAddCapability(Capability addedCapability); /** * Notify the Presenter that a Capability has been updated. */ public void onUpdateCapability(Capability updatedCapability); /** * Notify the Presenter that a Capability has been removed. */ public void onRemoveCapability(Capability removedCapability); /** * Notify the Presenter to update the order of capabilities. */ public void reorderCapabilities(List<Long> ids); /** * Request the Presenter begin refreshing the View's Capabilities list. (From * multiple onAdd/onRemove calls.) */ public void refreshView(); } /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** * Initialize user interface elements with the given components. */ public void setComponents(List<Component> components); /** * Initialize user interface elements with the given attributes. */ public void setAttributes(List<Attribute> attributes); /** * Initialize user interface elements with the given capabilities. */ public void setCapabilities(List<Capability> capabilities); public void setProjectLabels(Collection<String> labels); /** * Converts the view into a GWT widget. */ public Widget asWidget(); /** * Sets if this view is editable or not. * @param isEditable true if editable. */ public void setEditable(boolean isEditable); /** * Adds a capability to the view. * * @param capability capability to add. */ public void addCapability(Capability capability); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/CapabilitiesView.java
Java
asf20
2,991
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.DataRequestOption; import java.util.List; /** * View for a DataRequest widget. * {@See com.google.testing.testify.risk.frontend.model.DataRequest} * * @author chrsmith@google.com (Chris Smith) */ public interface DataRequestView { /** Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** Called when the user updates the DataRequest. */ public void onUpdate(List<DataRequestOption> newParameters); /** Called when the user deletes the given DataRequest. */ public void onRemove(); /** Requests the presenter refresh the view's controls. */ public void refreshView(); } /** Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** Set the UI to display the Component's name. */ public void setDataSourceName(String componentName); /** * Update the UI to display the data source parameters. * @param keyValues the set of allowable key values. null if arbitrary keys allowed. * @param parameters set of key/value pairs making up the data source's parameters. **/ public void setDataSourceParameters(List<String> keyValues, List<DataRequestOption> parameters); /** Hides the Widget so it is no longer visible. (Typically after it has been deleted.) */ public void hide(); /** Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/DataRequestView.java
Java
asf20
2,208
// 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.client.view.impl; import com.google.common.collect.HashMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Sets; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.HasValueChangeHandlers; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; import com.google.testing.testify.risk.frontend.client.view.RiskView; import com.google.testing.testify.risk.frontend.client.view.widgets.EasyDisclosurePanel; import com.google.testing.testify.risk.frontend.client.view.widgets.PageSectionVerticalPanel; 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.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Pair; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; /** * Base Widget for displaying Risk and/or Mitigation. (A glorified 2D heat map.) The control acts * as a repository of project Attributes, Components, and Capabilities so that future * risk providers can rely on that data to do visualization. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ public abstract class RiskViewImpl extends Composite implements RiskView, HasValueChangeHandlers<Pair<Integer, Integer>> { /** Enum for tracking the required pieces of information to fully initialize a risk view. */ private enum RequiredDataType { ATTRIBUTES, COMPONENTS, CAPABILITIES } /** * Used to wire parent class to associated UI Binder. */ interface RiskViewImplUiBinder extends UiBinder<Widget, RiskViewImpl> { } private static final RiskViewImplUiBinder uiBinder = GWT.create(RiskViewImplUiBinder.class); @UiField public PageSectionVerticalPanel pageSectionPanel; @UiField public Label introTextLabel; @UiField public Grid baseGrid; /** Panel to hold custom content from a derived class. */ @UiField public VerticalPanel content; /** Panel to hold custom content at the bottom of the widget. */ @UiField public SimplePanel bottomContent; /** * Map of intersection key to data stored inside a CapabilityIntersectionData object. */ private final Map<Integer, CapabilityIntersectionData> dataMap = Maps.newHashMap(); /** * Map of intersection key to capability list. */ private final Multimap<Integer, Capability> capabilityMap = HashMultimap.create(); private final HashSet<RequiredDataType> initializedDataTypes = Sets.newHashSet(); private final ArrayList<Component> components = Lists.newArrayList(); private final ArrayList<Attribute> attributes = Lists.newArrayList(); private Pair<Integer, Integer> selectedCell; /** * Constructs a new instance of the RiskViewImpl widget. For the UI to display something, call * {@link #setComponents(List)}, {@link #setAttributes(List)}, and {@link #setCapabilities(List)} * next. */ public RiskViewImpl() { initWidget(uiBinder.createAndBindUi(this)); setPageText("", ""); } @UiFactory public EasyDisclosurePanel createDisclosurePanel() { Label header = new Label("Risk displayed by Attribute and Component"); header.addStyleName("tty-DisclosureHeader"); return new EasyDisclosurePanel(header); } /** * Sets the risk page's introductory text. * * @param titleText the text displayed on the top, for example "Risk Factors". * @param introText the page text, explaining what the data illustrates. */ protected void setPageText(String titleText, String introText) { pageSectionPanel.setHeaderText(titleText); introTextLabel.setText(introText); } @Override public void setComponents(List<Component> components) { this.components.clear(); this.components.addAll(components); initializedDataTypes.add(RequiredDataType.COMPONENTS); initializeGrid(); initializeRiskCells(); } @Override public void setAttributes(List<Attribute> attributes) { this.attributes.clear(); this.attributes.addAll(attributes); initializedDataTypes.add(RequiredDataType.ATTRIBUTES); initializeGrid(); initializeRiskCells(); } @Override public void setCapabilities(List<Capability> newCapabilities) { capabilityMap.clear(); for (Capability capability : newCapabilities) { capabilityMap.put(capability.getCapabilityIntersectionKey(), capability); } initializedDataTypes.add(RequiredDataType.CAPABILITIES); initializeRiskCells(); } /** * Called for derived classes once the risk view has been fully initilzied. (All Attributes, * Components, and Capabilities have been specified.) */ protected abstract void onInitialized(); @Override public Widget asWidget() { return this; } /** * Initializes the Risk grid headers. */ void initializeGrid() { // We need both attributes and components for this control to make sense. if ((!initializedDataTypes.contains(RequiredDataType.ATTRIBUTES)) || (!initializedDataTypes.contains(RequiredDataType.COMPONENTS))) { return; } baseGrid.clear(); baseGrid.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { cellClicked(baseGrid.getCellForEvent(event)); } }); baseGrid.resize(components.size() + 1, attributes.size() + 1); CellFormatter formatter = baseGrid.getCellFormatter(); formatter.setStyleName(0, 0, "tty-GridXHeaderCell"); // Initialize the column and row headers. for (int cIndex = 0; cIndex < components.size(); cIndex++) { Label headerLabel = new Label(components.get(cIndex).getName()); formatter.setStyleName(cIndex + 1, 0, "tty-GridXHeaderCell"); baseGrid.setWidget(cIndex + 1, 0, headerLabel); } for (int aIndex = 0; aIndex < attributes.size(); aIndex++) { Label headerLabel = new Label(attributes.get(aIndex).getName()); formatter.setStyleName(0, aIndex + 1, "tty-GridYHeaderCell"); baseGrid.setWidget(0, aIndex + 1, headerLabel); } // Initialize the data rows. for (int cIndex = 0; cIndex < components.size(); cIndex++) { for (int aIndex = 0; aIndex < attributes.size(); aIndex++) { HTML html = new HTML("&nbsp;"); baseGrid.setWidget(cIndex + 1, aIndex + 1, html); } } } /** * Determines if all information necessary for the grid has been loaded from the server. * * @return true if fully loaded, false if not. */ protected boolean isInitialized() { // Make sure all required pieces of data are available. for (RequiredDataType type : RequiredDataType.values()) { if (!initializedDataTypes.contains(type)) { return false; } } return true; } /** * Executes on clicking a cell. * * @param cell the cell clicked on. */ private void cellClicked(HTMLTable.Cell cell) { if (cell != null) { int row = cell.getRowIndex(); int column = cell.getCellIndex(); // Ignore headers. if (row > 0 && column > 0) { // Unhighlight currently selected cell. if (selectedCell != null) { baseGrid.getCellFormatter().removeStyleName(selectedCell.getFirst(), selectedCell.getSecond(), "tty-RiskCellSelected"); } baseGrid.getCellFormatter().addStyleName(row, column, "tty-RiskCellSelected"); selectedCell = new Pair<Integer, Integer>(row, column); ValueChangeEvent.fire(this, selectedCell); } } } /** * Returns the CapabilityIntersectionData for a given row and column. * * @param row the row of the table you're interested in. * @param column the column of the table you're interested in. * @return data. */ protected CapabilityIntersectionData getDataForCell(int row, int column) { int cIndex = row - 1; int aIndex = column - 1; if (aIndex < 0 || aIndex >= attributes.size() || cIndex < 0 || cIndex >= components.size()) { return null; } Attribute attribute = attributes.get(aIndex); Component component = components.get(cIndex); Integer key = Capability.getCapabilityIntersectionKey(component, attribute); return dataMap.get(key); } /** * Initialize the riskProviderCells field. (Maybe called more than once as asynchronous calls get * returned.) */ private void initializeRiskCells() { if (!isInitialized()) { return; } for (Attribute attribute : attributes) { for (Component component : components) { Integer key = Capability.getCapabilityIntersectionKey(component, attribute); CapabilityIntersectionData data = new CapabilityIntersectionData( attribute, component, capabilityMap.get(key)); dataMap.put(key, data); } } // Notify derived classes the risk view has been fully initialized, and is ready for painting. onInitialized(); } /** * Refreshes the risk data for all cells, based on the risk provided by the passed in risk * provider. * * @param provider provider that determines risk. */ protected void refreshRiskCalculation(RiskProvider provider) { if (provider == null) { return; } refreshRiskCalculation(Lists.newArrayList(provider)); } /** * Refreshes the risk data for all cells, based on the risk provided by the passed in risk * providers. * * @param providers providers that determines risk (risk is additive). */ protected void refreshRiskCalculation(List<RiskProvider> providers) { for (int cIndex = 0; cIndex < components.size(); cIndex++) { for (int aIndex = 0; aIndex < attributes.size(); aIndex++) { int row = cIndex + 1; int column = aIndex + 1; Attribute attribute = attributes.get(aIndex); Component component = components.get(cIndex); Integer key = Capability.getCapabilityIntersectionKey(component, attribute); CapabilityIntersectionData data = dataMap.get(key); double risk = 0.0; double mitigations = 0.0; // TODO(jimr): RiskProvider would be better off exposing a type instead of doing it based // off the returned positive/negative. for (RiskProvider provider : providers) { double sourceRisk = provider.calculateRisk(data); if (sourceRisk < 0) { mitigations += sourceRisk; } else { risk += sourceRisk; } } updateCell(row, column, risk, mitigations); } } } /** * Updates a cell with a new risk value. * * @param row the cell's row. * @param column the cell's column. * @param risk the new risk value. * @param mitigations the new mitigation value. */ private void updateCell(int row, int column, double risk, double mitigations) { // Mitigations and risk don't need to be separate, but this gives us flexibility in the future. double totalRisk = risk + mitigations; int intensity = (int) (totalRisk * 10.0) * 10; if (intensity > 100) { intensity = 100; } else if (intensity < -100) { intensity = -100; } String intensityCss = "tty-RiskIntensity_" + Integer.toString(intensity); baseGrid.getCellFormatter().setStyleName(row, column, "tty-GridCell"); baseGrid.getCellFormatter().addStyleName(row, column, intensityCss); } /** * Retreive a list of data for all intersection points. * * @return list of CapabilityIntersectionData objects for all intersections on the grid. */ protected List<CapabilityIntersectionData> getIntersectionData() { return Lists.newArrayList(dataMap.values()); } @Override public HandlerRegistration addValueChangeHandler( ValueChangeHandler<Pair<Integer, Integer>> handler) { return addHandler(handler, ValueChangeEvent.getType()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/RiskViewImpl.java
Java
asf20
13,645
// 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.client.view.impl; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedEvent; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedHandler; import com.google.testing.testify.risk.frontend.client.presenter.ComponentPresenter; import com.google.testing.testify.risk.frontend.client.view.ComponentsView; import com.google.testing.testify.risk.frontend.client.view.widgets.SortableVerticalPanel; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Signoff; import java.util.Collection; import java.util.List; import java.util.Map; /** * A widget for controlling the Components page of a project. * * @author chrsmith@google.com (Chris Smith) */ public class ComponentsViewImpl extends Composite implements ComponentsView { interface ComponentsViewImplUiBinder extends UiBinder<Widget, ComponentsViewImpl> {} private static final ComponentsViewImplUiBinder uiBinder = GWT.create(ComponentsViewImplUiBinder.class); @UiField public SortableVerticalPanel<ComponentViewImpl> componentsPanel; @UiField public HorizontalPanel addNewComponentPanel; @UiField public TextBox newComponentName; @UiField public Button addNewComponentButton; // Handle to the underlying Presenter corresponding to this View. private Presenter presenter; private boolean editingEnabled; private final Collection<String> projectLabels = Lists.newArrayList(); private Map<Long, Boolean> signedOff = Maps.newHashMap(); private Map<Long, ComponentPresenter> childPresenters = Maps.newHashMap(); /** * Constructs a ProjectSettings object. */ public ComponentsViewImpl() { initWidget(uiBinder.createAndBindUi(this)); // When the widget list is reordered, notify the presenter. componentsPanel.addWidgetsReorderedHandler( new WidgetsReorderedHandler() { @Override public void onWidgetsReordered(WidgetsReorderedEvent event) { List<Long> attributeIDs = Lists.newArrayList(); for (Widget widget : event.getWidgetOrdering()) { attributeIDs.add(((ComponentViewImpl) widget).getComponentId()); } if (presenter != null) { presenter.reorderComponents(attributeIDs); } } }); // TODO(jimr): Update this when/if GWT supports setting attributes on textboxes directly. newComponentName.getElement().setAttribute("placeholder", "Add a new component..."); } /** * Returns a new Component widget to be displayed on the componentsList. */ private ComponentViewImpl createComponentWidget(Component component) { ComponentViewImpl componentView = new ComponentViewImpl(); if (editingEnabled) { componentView.enableEditing(); } Boolean checked = signedOff.get(component.getComponentId()); componentView.setSignedOff(checked == null ? false : checked); componentView.setLabelSuggestions(projectLabels); ComponentPresenter componentPresenter = new ComponentPresenter( component, componentView, this.presenter); childPresenters.put(component.getComponentId(), componentPresenter); return componentView; } /** * Handler for hitting enter in the new component text box. */ @UiHandler("newComponentName") protected void onComponentNameEnter(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { addNewComponentButton.click(); } } /** * Handler for the addNewComponentButton's click event. Adds a new project Component. */ @UiHandler("addNewComponentButton") protected void onAddNewComponentButtonClicked(ClickEvent event) { if (newComponentName.getText().trim().length() == 0) { Window.alert("Error: Please enter a Component name."); return; } // Create new Component and attach to UI Component newComponent = new Component(presenter.getProjectId()); newComponent.setName(newComponentName.getText()); presenter.createComponent(newComponent); // Upon creation the presenter will do a full refresh. No need to rebuild the Component list. newComponentName.setText(""); } /** * Binds this View to the given Presenter. */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } /** * Updates the UI to display the given set of Components. */ @Override public void setProjectComponents(List<Component> components) { List<ComponentViewImpl> componentWidgets = Lists.newArrayList(); for (Component component : components) { componentWidgets.add(createComponentWidget(component)); } // Build the widgets list. componentsPanel.setWidgets(componentWidgets, new Function<ComponentViewImpl, Widget>() { @Override public Widget apply(ComponentViewImpl arg) { return arg.componentGripper; } }); } @Override public void refreshComponent(Component component) { ComponentPresenter childPresenter = childPresenters.get(component.getComponentId()); childPresenter.refreshView(component); } @Override public void setSignoffs(List<Signoff> signoffs) { signedOff.clear(); if (signoffs != null) { for (Signoff s : signoffs) { signedOff.put(s.getElementId(), s.getSignedOff()); } } for (Widget w : componentsPanel) { ComponentViewImpl view = (ComponentViewImpl) w; Boolean checked = signedOff.get(view.getComponentId()); view.setSignedOff(checked == null ? false : checked); } } @Override public void setProjectLabels(Collection<String> projectLabels) { this.projectLabels.clear(); this.projectLabels.addAll(projectLabels); for (Widget w : componentsPanel) { AttributeViewImpl view = (AttributeViewImpl) w; view.setLabelSuggestions(this.projectLabels); } } @Override public void enableEditing() { editingEnabled = true; addNewComponentPanel.setVisible(true); // Go through any existing components being displayed, and set their 'readwrite' flag. for (Widget widget : componentsPanel) { if (widget.getClass().equals(ComponentViewImpl.class)) { ((ComponentViewImpl) widget).enableEditing(); } } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ComponentsViewImpl.java
Java
asf20
7,727
// 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.client.view.impl; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; import com.google.testing.testify.risk.frontend.client.view.ComponentView; import com.google.testing.testify.risk.frontend.client.view.widgets.EditableLabel; import com.google.testing.testify.risk.frontend.client.view.widgets.LabelWidget; import com.google.testing.testify.risk.frontend.model.AccLabel; import java.util.Collection; import java.util.List; //TODO(chrsmith): Merge ComponentViewImpl and AttributeViewImpl into a single widget. /** * Widget for displaying a Component. * * @author chrsmith@google.com (Chris Smith) */ public class ComponentViewImpl extends Composite implements ComponentView { /** * Used to wire parent class to associated UI Binder. */ interface ComponentViewImplUiBinder extends UiBinder<Widget, ComponentViewImpl> { } private static final ComponentViewImplUiBinder uiBinder = GWT.create(ComponentViewImplUiBinder.class); @UiField protected Label componentGripper; @UiField protected EditableLabel componentName; @UiField protected TextArea description; @UiField protected Label componentId; @UiField protected Image deleteComponentImage; @UiField protected FlowPanel labelsPanel; @UiField protected CheckBox signoffBox; private LabelWidget addLabelWidget; /** Presenter associated with this View */ private Presenter presenter; private final Collection<String> labelSuggestions = Lists.newArrayList(); private boolean editingEnabled; public ComponentViewImpl() { initWidget(uiBinder.createAndBindUi(this)); description.getElement().setAttribute("placeholder", "Enter description of this component..."); } @UiHandler("signoffBox") protected void onSignoffClicked(ClickEvent event) { presenter.updateSignoff(signoffBox.getValue()); } /** Wires renaming the Component in the UI to the backing presenter. */ @UiHandler("componentName") protected void onComponentNameChanged(ValueChangeEvent<String> event) { if (presenter != null) { if (event.getValue().length() == 0) { NotificationUtil.displayErrorMessage("Invalid name for Component."); presenter.refreshView(); } else { presenter.onRename(event.getValue()); } } } @UiHandler("description") protected void onDescriptionChange(ChangeEvent event) { presenter.onDescriptionEdited(description.getText()); } /** * Handler for the deleteComponentImage's click event, removing the Component. */ @UiHandler("deleteComponentImage") protected void onDeleteComponentImageClicked(ClickEvent event) { String promptText = "Are you sure you want to remove " + componentName.getText() + "?"; if (Window.confirm(promptText)) { presenter.onRemove(); } } /** * Updates the label suggestions for all labels on this view. */ public void setLabelSuggestions(Collection<String> labelSuggestions) { this.labelSuggestions.clear(); this.labelSuggestions.addAll(labelSuggestions); for (Widget w : labelsPanel) { if (w instanceof LabelWidget) { LabelWidget l = (LabelWidget) w; l.setLabelSuggestions(this.labelSuggestions); } } } /** * Displays a new Component Label on this Widget. */ public void displayLabel(final AccLabel label) { final LabelWidget labelWidget = new LabelWidget(label.getLabelText()); labelWidget.setLabelSuggestions(labelSuggestions); labelWidget.setEditable(editingEnabled); labelWidget.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { if (event.getValue() == null) { labelsPanel.remove(labelWidget); presenter.onRemoveLabel(label); } else { presenter.onUpdateLabel(label, event.getValue()); } } }); labelsPanel.add(labelWidget); } /** * Updates the UI with the given Component name. */ @Override public void setComponentName(String name) { componentName.setText(name); } @Override public void setDescription(String description) { this.description.setText(description == null ? "" : description); } /** * Updates the UI with the given Component ID. */ @Override public void setComponentId(Long id) { componentId.setText(id.toString()); } /** * Initialize this View's Presenter object. (For two-way communication.) */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public Widget asWidget() { return this; } /** * Hides the given Widget, equivalent to setVisible(false). */ @Override public void hide() { this.setVisible(false); } /** * Updates the Widget's list of Component Labels. */ @Override public void setComponentLabels(List<AccLabel> labels) { labelsPanel.clear(); for (AccLabel label : labels) { displayLabel(label); } addBlankLabel(); } private void addBlankLabel() { final String newText = "new label"; addLabelWidget = new LabelWidget(newText, true); addLabelWidget.setLabelSuggestions(labelSuggestions); addLabelWidget.setVisible(editingEnabled); addLabelWidget.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { presenter.onAddLabel(event.getValue()); labelsPanel.remove(addLabelWidget); addBlankLabel(); } }); addLabelWidget.setEditable(true); labelsPanel.add(addLabelWidget); } @Override public void enableEditing() { editingEnabled = true; componentGripper.setVisible(true); componentName.setReadOnly(false); signoffBox.setEnabled(true); deleteComponentImage.setVisible(true); description.setEnabled(true); for (Widget widget : labelsPanel) { LabelWidget label = (LabelWidget) widget; label.setEditable(true); } if (addLabelWidget != null) { addLabelWidget.setVisible(true); } } @Override public void setSignedOff(boolean signedOff) { signoffBox.setValue(signedOff); } /** Returns the ID of the underlying Component if applicable. Otherwise returns -1. */ public long getComponentId() { try { return Long.parseLong(componentId.getText()); } catch (NumberFormatException nfe) { return -1; } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ComponentViewImpl.java
Java
asf20
7,960
// 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.client.view.impl; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedEvent; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedHandler; import com.google.testing.testify.risk.frontend.client.presenter.AttributePresenter; import com.google.testing.testify.risk.frontend.client.view.AttributesView; import com.google.testing.testify.risk.frontend.client.view.widgets.SortableVerticalPanel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Signoff; import java.util.Collection; import java.util.List; import java.util.Map; /** * A widget for controlling the Attributes of a project. * * @author jimr@google.com (Jim Reardon) */ public class AttributesViewImpl extends Composite implements AttributesView { interface AttributesViewImplUiBinder extends UiBinder<Widget, AttributesViewImpl> {} private static final AttributesViewImplUiBinder uiBinder = GWT.create(AttributesViewImplUiBinder.class); @UiField public SortableVerticalPanel<AttributeViewImpl> attributesPanel; @UiField public HorizontalPanel addNewAttributePanel; @UiField public TextBox newAttributeName; @UiField public Button addNewAttributeButton; // Handle to the underlying Presenter corresponding to this View. private Presenter presenter; private boolean editingEnabled; private final Collection<String> projectLabels = Lists.newArrayList(); private Map<Long, Boolean> signedOff = Maps.newHashMap(); private Map<Long, AttributePresenter> childPresenters = Maps.newHashMap(); /** * Constructs a ProjectSettings object. */ public AttributesViewImpl() { initWidget(uiBinder.createAndBindUi(this)); // When the widget list is reordered, notify the presenter. attributesPanel.addWidgetsReorderedHandler( new WidgetsReorderedHandler() { @Override public void onWidgetsReordered(WidgetsReorderedEvent event) { List<Long> attributeIDs = Lists.newArrayList(); for (Widget widget : event.getWidgetOrdering()) { attributeIDs.add(((AttributeViewImpl) widget).getAttributeId()); } if (presenter != null) { presenter.reorderAttributes(attributeIDs); } } }); // TODO(jimr): Update this when/if GWT supports setting attributes on textboxes directly. newAttributeName.getElement().setAttribute("placeholder", "Add a new attribute..."); } /** * Handler for hitting enter in the new attribute text box. */ @UiHandler("newAttributeName") void onAttributeNameEnter(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { addNewAttributeButton.click(); } } /** * Handler for the addNewAttributeButton's click event. Adds a new project Attribute. */ @UiHandler("addNewAttributeButton") void onAddNewAttributeButtonClicked(ClickEvent event) { if (newAttributeName.getText().trim().length() == 0) { Window.alert("Error: Please enter a name for the Attribute."); return; } // Create new Attribute and attach to UI Attribute newAttribute = new Attribute(); newAttribute.setParentProjectId(presenter.getProjectId()); newAttribute.setName(newAttributeName.getText()); presenter.createAttribute(newAttribute); newAttributeName.setText(""); // Don't display the new attribute widget. Instead, wait for a full refresh from the presenter. } private AttributeViewImpl createAttributeWidget(Attribute attribute) { AttributeViewImpl attributeView = new AttributeViewImpl(); if (editingEnabled) { attributeView.enableEditing(); } AttributePresenter attributePresenter = new AttributePresenter( attribute, attributeView, this.presenter); childPresenters.put(attribute.getAttributeId(), attributePresenter); Boolean checked = signedOff.get(attribute.getAttributeId()); attributeView.setSignedOff(checked == null ? false : checked); attributeView.setLabelSuggestions(projectLabels); return attributeView; } /** * Binds this View to the given Presenter. */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } /** * Updates the UI to display the given set of Attributes. */ @Override public void setProjectAttributes(List<Attribute> attributes) { List<AttributeViewImpl> attributeWidgets = Lists.newArrayList(); for (Attribute attribute : attributes) { attributeWidgets.add(createAttributeWidget(attribute)); } // Build the widgets list. attributesPanel.setWidgets(attributeWidgets, new Function<AttributeViewImpl, Widget>() { @Override public Widget apply(AttributeViewImpl arg) { return arg.attributeGripper; } }); } @Override public void refreshAttribute(Attribute attribute) { AttributePresenter presenter = childPresenters.get(attribute.getAttributeId()); presenter.refreshView(attribute); } @Override public void setSignoffs(List<Signoff> signoffs) { signedOff.clear(); if (signoffs != null) { for (Signoff s : signoffs) { signedOff.put(s.getElementId(), s.getSignedOff()); } } for (Widget w : attributesPanel) { AttributeViewImpl view = (AttributeViewImpl) w; Boolean checked = signedOff.get(view.getAttributeId()); view.setSignedOff(checked == null ? false : checked); } } @Override public void setProjectLabels(Collection<String> projectLabels) { this.projectLabels.clear(); this.projectLabels.addAll(projectLabels); for (Widget w : attributesPanel) { AttributeViewImpl view = (AttributeViewImpl) w; view.setLabelSuggestions(this.projectLabels); } } @Override public void enableEditing() { editingEnabled = true; addNewAttributePanel.setVisible(true); // Go through any existing attributes being displayed, and set their 'readwrite' flag. for (Widget widget : attributesPanel) { if (widget.getClass().equals(AttributeViewImpl.class)) { ((AttributeViewImpl) widget).enableEditing(); } } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/AttributesViewImpl.java
Java
asf20
7,648
// 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.client.view.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.presenter.FilterPresenter; import com.google.testing.testify.risk.frontend.client.view.ConfigureFiltersView; import com.google.testing.testify.risk.frontend.client.view.FilterView; import com.google.testing.testify.risk.frontend.model.DatumType; import com.google.testing.testify.risk.frontend.model.Filter; import java.util.List; import java.util.Map; /** * View that shows all filters and lets you create a new one. * * A {@link 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) */ public class ConfigureFiltersViewImpl extends Composite implements ConfigureFiltersView { interface ConfigureFiltersImplUiBinder extends UiBinder<Widget, ConfigureFiltersViewImpl> {} private static final ConfigureFiltersImplUiBinder uiBinder = GWT.create(ConfigureFiltersImplUiBinder.class); @UiField public VerticalPanel filtersPanel; @UiField public ListBox filterTypeBox; @UiField public Button addFilterButton; private List<Filter> filters; // These are needed as options for the Filter widgets. private Map<String, Long> attributes; private Map<String, Long> components; private Map<String, Long> capabilities; private Presenter presenter; public ConfigureFiltersViewImpl() { initWidget(uiBinder.createAndBindUi(this)); filterTypeBox.clear(); for (DatumType type : DatumType.values()) { filterTypeBox.addItem(type.getPlural(), type.name()); } } @UiHandler("addFilterButton") public void handleAddFilterButtonClicked(ClickEvent event) { if (presenter != null) { Filter filter = new Filter(); String selected = filterTypeBox.getValue(filterTypeBox.getSelectedIndex()); filter.setFilterType(DatumType.valueOf(selected)); presenter.addFilter(filter); } } @Override public void setFilters(List<Filter> filters) { this.filters = filters; updateFilters(); } private void updateFilters() { if (attributes != null && components != null && capabilities != null) { filtersPanel.clear(); for (Filter filter : filters) { FilterView view = new FilterViewImpl(); FilterPresenter filterPresenter = new FilterPresenter(filter, attributes, components, capabilities, view, presenter); filtersPanel.add(view.asWidget()); } } } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public void setAttributes(Map<String, Long> attributes) { this.attributes = attributes; updateFilters(); } @Override public void setCapabilities(Map<String, Long> capabilities) { this.capabilities = capabilities; updateFilters(); } @Override public void setComponents(Map<String, Long> components) { this.components = components; updateFilters(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ConfigureFiltersViewImpl.java
Java
asf20
4,168
// 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.client.view.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.safehtml.shared.SafeHtmlUtils; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent; import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent.DialogResult; import com.google.testing.testify.risk.frontend.client.event.DialogClosedHandler; import com.google.testing.testify.risk.frontend.client.view.ProjectSettingsView; import com.google.testing.testify.risk.frontend.client.view.widgets.PageSectionVerticalPanel; import com.google.testing.testify.risk.frontend.client.view.widgets.StandardDialogBox; import com.google.testing.testify.risk.frontend.model.Project; 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; /** * A widget for controlling the settings of a project. * * @author chrsmith@google.com (Chris Smith) */ public class ProjectSettingsViewImpl extends Composite implements ProjectSettingsView { interface ProjectSettingsViewImplUiBinder extends UiBinder<Widget, ProjectSettingsViewImpl> {} private static final ProjectSettingsViewImplUiBinder uiBinder = GWT.create(ProjectSettingsViewImplUiBinder.class); @UiField public TextBox projectName; @UiField public TextArea projectDescription; @UiField public CheckBox projectIsPublicCheckBox; @UiField public TextBox projectOwnersTextBox; @UiField public TextArea projectEditorsTextArea; @UiField public TextArea projectViewersTextArea; @UiField public Button updateProjectInfoButton; @UiField public HorizontalPanel savedPanel; @UiField public VerticalPanel publicPanel; @UiField public CheckBox deleteProjectCheckBox; @UiField PageSectionVerticalPanel deleteApplicationSection; // Handle to the underlying Presenter corresponding to this View. private Presenter presenter; private List<String> currentOwners; private List<String> currentEditors; private List<String> currentViewers; /** * Constructs a ProjectSettings object. */ public ProjectSettingsViewImpl() { initWidget(uiBinder.createAndBindUi(this)); } @UiHandler("projectOwnersTextBox") protected void onOwnersChange(ChangeEvent event) { projectOwnersTextBox.setText(StringUtil.trimAndReformatCsv(projectOwnersTextBox.getText())); } @UiHandler("projectEditorsTextArea") protected void onEditorsChange(ChangeEvent event) { projectEditorsTextArea.setText(StringUtil.trimAndReformatCsv(projectEditorsTextArea.getText())); } @UiHandler("projectViewersTextArea") protected void onViewersChange(ChangeEvent event) { projectViewersTextArea.setText(StringUtil.trimAndReformatCsv(projectViewersTextArea.getText())); } /** * Handler for the updateProjectInfoButton's click event. */ @UiHandler("updateProjectInfoButton") protected void onUpdateProjectInfoButtonClicked(ClickEvent event) { savedPanel.setVisible(false); updateProjectInfoButton.setEnabled(false); if (presenter != null) { if (deleteProjectCheckBox.getValue()) { presenter.removeProject(); reloadPage(); } else { final List<String> newOwners = StringUtil.csvToList(projectOwnersTextBox.getText()); final List<String> newEditors = StringUtil.csvToList(projectEditorsTextArea.getText()); final List<String> newViewers = StringUtil.csvToList(projectViewersTextArea.getText()); if (newOwners.size() < 1) { Window.alert("Error: The project must have at least one owner."); return; } StringBuilder warning = new StringBuilder(); List<String> difference = StringUtil.subtractList(newOwners, currentOwners); if (difference.size() > 0) { warning.append("<br><br><b>Added owners:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } difference = StringUtil.subtractList(currentOwners, newOwners); if (difference.size() > 0) { warning.append("<br><br><b>Removed owners:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } difference = StringUtil.subtractList(newEditors, currentEditors); if (difference.size() > 0) { warning.append("<br><br><b>Added editors:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } difference = StringUtil.subtractList(currentEditors, newEditors); if (difference.size() > 0) { warning.append("<br><br><b>Removed editors:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } difference = StringUtil.subtractList(newViewers, currentViewers); if (difference.size() > 0) { warning.append("<br><br><b>Added viewers:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } difference = StringUtil.subtractList(currentViewers, newViewers); if (difference.size() > 0) { warning.append("<br><br><b>Removed viewers:</b> "); warning.append(SafeHtmlUtils.htmlEscape(StringUtil.listToCsv(difference))); } // If there's a warning to save, then display it and require confirmation before saving. // Otherwise, just save. if (warning.length() > 0) { StandardDialogBox box = new StandardDialogBox(); box.setTitle("Permission Changes"); box.add(new HTML("You are changing some of the permissions for this project." + warning.toString() + "<br><br>")); box.addDialogClosedHandler(new DialogClosedHandler() { @Override public void onDialogClosed(DialogClosedEvent event) { if (event.getResult().equals(DialogResult.OK)) { presenter.onUpdateProjectInfoClicked(projectName.getText(), projectDescription.getText(), newOwners, newEditors, newViewers, projectIsPublicCheckBox.getValue()); currentOwners = newOwners; currentEditors = newEditors; currentViewers = newViewers; } else { updateProjectInfoButton.setEnabled(true); } } }); StandardDialogBox.showAsDialog(box); } else { presenter.onUpdateProjectInfoClicked(projectName.getText(), projectDescription.getText(), newOwners, newEditors, newViewers, projectIsPublicCheckBox.getValue()); } } } } @Override public void showSaved() { updateProjectInfoButton.setEnabled(true); savedPanel.setVisible(true); Timer timer = new Timer() { @Override public void run() { savedPanel.setVisible(false); } }; // Make the saved item disappear after 10 seconds. timer.schedule(10000); } /** * Handler for the deleteProjectButton's click event. Deletes the project. */ @UiHandler("deleteProjectCheckBox") void onDeleteProjectCheckBoxChecked(ClickEvent event) { String warningMessage = "This will permanently delete your project when you click save." + " Are you sure?"; if (!Window.confirm(warningMessage)) { deleteProjectCheckBox.setValue(false); } } /** * Reloads the current web page. */ public void reloadPage() { History.newItem("/homepage"); } /** * Binds this View to the given Presenter. */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } /** Updates the view to enable editing project data given the access level. */ @Override public void enableProjectEditing(ProjectAccess userAccessLevel) { // Enable certain controls only if they have OWNER access. if (userAccessLevel.hasAccess(ProjectAccess.OWNER_ACCESS)) { projectOwnersTextBox.setEnabled(true); deleteApplicationSection.setVisible(true); publicPanel.setVisible(true); } // Enable other widgets only if they have EDIT access. if (userAccessLevel.hasAccess(ProjectAccess.EDIT_ACCESS)) { projectName.setEnabled(true); projectDescription.setEnabled(true); projectEditorsTextArea.setEnabled(true); projectViewersTextArea.setEnabled(true); updateProjectInfoButton.setEnabled(true); } } /** * Updates the UI with the given project information. */ @Override public void setProjectSettings(Project projectInformation) { currentOwners = projectInformation.getProjectOwners(); currentEditors = projectInformation.getProjectEditors(); currentViewers = projectInformation.getProjectViewers(); projectName.setText(projectInformation.getName()); projectDescription.setText(projectInformation.getDescription()); projectOwnersTextBox.setText(StringUtil.listToCsv(currentOwners)); projectEditorsTextArea.setText(StringUtil.listToCsv(currentEditors)); projectViewersTextArea.setText(StringUtil.listToCsv(currentViewers)); projectIsPublicCheckBox.setValue(projectInformation.getIsPubliclyVisible()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ProjectSettingsViewImpl.java
Java
asf20
10,735
// 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.client.view.impl; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; import com.google.testing.testify.risk.frontend.client.riskprovider.impl.BugRiskProvider; import com.google.testing.testify.risk.frontend.client.riskprovider.impl.CodeChurnRiskProvider; import com.google.testing.testify.risk.frontend.client.riskprovider.impl.StaticRiskProvider; import com.google.testing.testify.risk.frontend.client.riskprovider.impl.TestCoverageRiskProvider; import com.google.testing.testify.risk.frontend.client.view.widgets.LinkCapabilityWidget; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.model.Pair; import java.util.List; /** * View of mitigated risk for a project. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ public class KnownRiskViewImpl extends RiskViewImpl { /** * Stores details on a risk provider along with a checkbox indicating its state. */ private class SourceItem { private final RiskProvider provider; private final CheckBox checkBox; public SourceItem(RiskProvider provider, CheckBox checkBox) { this.provider = provider; this.checkBox = checkBox; } public RiskProvider getProvider() { return provider; } public CheckBox getCheckBox() { return checkBox; } } /** Panel to hold all of the check boxes associated with Risk sources. */ private final HorizontalPanel sourcesPanel = new HorizontalPanel(); /** Panel to hold the risk page's content. */ private final HorizontalPanel contentPanel = new HorizontalPanel(); private final List<SourceItem> sources = Lists.newArrayList(); public KnownRiskViewImpl() { String introText = "This shows the Total Risk to your application, taking into account any Risk Sources " + "as well as Mitigation Sources that are checked below."; setPageText("Known Risk", introText); sourcesPanel.addStyleName("tty-RiskSourcesPanel"); contentPanel.add(sourcesPanel); this.content.add(contentPanel); addValueChangeHandler( new ValueChangeHandler<Pair<Integer, Integer>>() { @Override public void onValueChange(ValueChangeEvent<Pair<Integer, Integer>> event) { CapabilityIntersectionData cellData = getDataForCell( event.getValue().first, event.getValue().second); bottomContent.clear(); bottomContent.setWidget(createBottomWidget(cellData)); } }); } private Widget createBottomWidget(CapabilityIntersectionData data) { VerticalPanel panel = new VerticalPanel(); panel.setStyleName("tty-ItemContainer"); String aName = data.getParentAttribute().getName(); String cName = data.getParentComponent().getName(); Label name = new Label(cName + " is " + aName); name.setStyleName("tty-ItemName"); panel.add(name); for (Capability capability : data.getCapabilities()) { LinkCapabilityWidget widget = new LinkCapabilityWidget(capability); panel.add(widget); } return panel; } /** * Returns a CheckBox to control the RiskProvider (changing the check state regenerates the risk * grid's colors.) */ private CheckBox getRiskProviderCheckBox(RiskProvider provider) { CheckBox providerCheckBox = new CheckBox(provider.getName()); providerCheckBox.setValue(true); providerCheckBox.addValueChangeHandler( new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { refreshRiskCalculation(); } }); return providerCheckBox; } @Override protected void onInitialized() { List<RiskProvider> providers = Lists.newArrayList( new StaticRiskProvider(), new BugRiskProvider(), new CodeChurnRiskProvider(), new TestCoverageRiskProvider()); // Initialize risk sources. sources.clear(); sourcesPanel.clear(); for (RiskProvider provider : providers) { CheckBox providerCheckBox = getRiskProviderCheckBox(provider); sourcesPanel.add(providerCheckBox); SourceItem sourceItem = new SourceItem(provider, providerCheckBox); sources.add(sourceItem); } refreshRiskCalculation(); } /** * Initialize every cell in the table. This includes calculating the risk of every risk source * and mitigation and then viewing the delta. */ private void refreshRiskCalculation() { Predicate<SourceItem> getChecked = new Predicate<SourceItem>() { @Override public boolean apply(SourceItem input) { return input.getCheckBox().getValue(); }}; Function<SourceItem, RiskProvider> getProvider = new Function<SourceItem, RiskProvider>() { @Override public RiskProvider apply(SourceItem arg0) { return arg0.getProvider(); } }; List<RiskProvider> enabled = Lists.newArrayList( Iterables.transform( Iterables.filter(sources, getChecked), getProvider)); refreshRiskCalculation(enabled); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/KnownRiskViewImpl.java
Java
asf20
6,408
// 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.client.view.impl; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.view.FilterView; import com.google.testing.testify.risk.frontend.client.view.widgets.ConstrainedParameterWidget; import com.google.testing.testify.risk.frontend.model.FilterOption; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Implementation of FilterView. * * @author jimr@google.com (Jim Reardon) */ public class FilterViewImpl extends Composite implements FilterView { interface FilterViewImplUiBinder extends UiBinder<Widget, FilterViewImpl> {} private static final FilterViewImplUiBinder uiBinder = GWT.create(FilterViewImplUiBinder.class); @UiField protected Label filterName; @UiField protected ListBox anyOrAllBox; @UiField protected VerticalPanel filterOptions; @UiField protected Anchor addOptionLink; @UiField protected Button updateFilter; @UiField protected Button cancelUpdateFilter; @UiField protected Image deleteFilterImage; @UiField protected ListBox attributeBox; @UiField protected ListBox componentBox; @UiField protected ListBox capabilityBox; private Presenter presenter; private List<String> filterOptionChoices = Lists.newArrayList(); private Long attribute; private Long component; private Long capability; private static final String NONE_VALUE = "<< none >>"; public FilterViewImpl() { List<String> items = Lists.newArrayList(); initWidget(uiBinder.createAndBindUi(this)); anyOrAllBox.addItem("any", "any"); anyOrAllBox.addItem("all", "all"); } /** When the user clicks the 'add option' link, add a new option input to the end of the list. */ @UiHandler("addOptionLink") protected void handleAddOptionLinkClick(ClickEvent event) { filterOptions.add(createRequestWidget("", "")); } @UiHandler("updateFilter") void onUpdateFilterClicked(ClickEvent event) { ArrayList<FilterOption> options = Lists.newArrayList(); // Iterate through each widget on the Filter Options Vertical Panel, as each of those will be // a parameter to the filter. for (Widget widget : filterOptions) { ConstrainedParameterWidget param = (ConstrainedParameterWidget) widget; String type = param.getParameterKey(); String value = param.getParameterValue(); FilterOption option = new FilterOption(type, value); options.add(option); } String conjunction = anyOrAllBox.getValue(anyOrAllBox.getSelectedIndex()); attribute = stringToId(attributeBox.getValue(attributeBox.getSelectedIndex())); component = stringToId(componentBox.getValue(componentBox.getSelectedIndex())); capability = stringToId(capabilityBox.getValue(capabilityBox.getSelectedIndex())); presenter.onUpdate(options, conjunction, attribute, component, capability); } private ConstrainedParameterWidget createRequestWidget(String name, String value) { final ConstrainedParameterWidget param = new ConstrainedParameterWidget( filterOptionChoices, name, value); param.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent arg0) { filterOptions.remove(param); } }); return param; } // Will return NULL if the user has selected the NONE option, otherwise the string is parsed // into a Long. private Long stringToId(String string) { if (NONE_VALUE.equals(string)) { return null; } return Long.parseLong(string); } @UiHandler("cancelUpdateFilter") void onCancelUpdateFilterClicked(ClickEvent event) { presenter.refreshView(); } @UiHandler("deleteFilterImage") void onDeleteFilterImageClicked(ClickEvent event) { String promptText = "Are you sure you want to remove this filter?"; if (Window.confirm(promptText)) { presenter.onRemove(); } } @Override public void setFilterSettings(List<FilterOption> options, String conjunction, Long attribute, Long component, Long capability) { // Select the conjunctor they have set. selectInListBoxByValue(anyOrAllBox, conjunction); // Store the selected ACC parts. this.attribute = attribute; selectInListBoxByValue(attributeBox, attribute); this.component = component; selectInListBoxByValue(componentBox, component); this.capability = capability; selectInListBoxByValue(capabilityBox, capability); filterOptions.clear(); for (FilterOption option : options) { filterOptions.add(createRequestWidget(option.getType(), option.getValue())); } // If there's not a filter option yet, show an empty blank. if (options.size() < 1) { handleAddOptionLinkClick(null); } } private void selectInListBoxByValue(ListBox box, Long value) { selectInListBoxByValue(box, value == null ? null : value.toString()); } private void selectInListBoxByValue(ListBox box, String value) { // Default to first item, which in many boxes will be the none value. box.setSelectedIndex(0); for (int i = 0; i < box.getItemCount(); i++) { if (box.getValue(i).equals(value)) { box.setSelectedIndex(i); } } } @Override public Widget asWidget() { return this; } @Override public void hide() { setVisible(false); } @Override public void setFilterTitle(String title) { filterName.setText(title); } @Override public void setFilterOptionChoices(List<String> filterOptionChoices) { this.filterOptionChoices = filterOptionChoices; } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } private void populateAccBox(ListBox box, Map<String, Long> items) { box.clear(); box.addItem(NONE_VALUE, NONE_VALUE); for (String key : items.keySet()) { Long id = items.get(key); box.addItem(key, id.toString()); } } @Override public void setAttributes(Map<String, Long> attributes) { populateAccBox(attributeBox, attributes); selectInListBoxByValue(attributeBox, attribute); } @Override public void setCapabilities(Map<String, Long> capabilities) { populateAccBox(capabilityBox, capabilities); selectInListBoxByValue(capabilityBox, capability); } @Override public void setComponents(Map<String, Long> components) { populateAccBox(componentBox, components); selectInListBoxByValue(componentBox, component); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/FilterViewImpl.java
Java
asf20
7,877
// 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.client.view.impl; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DisclosurePanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.view.CapabilityDetailsView; import com.google.testing.testify.risk.frontend.client.view.widgets.EditCapabilityWidget; import com.google.testing.testify.risk.frontend.client.view.widgets.PageSectionVerticalPanel; 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.UploadedDatum; import com.google.testing.testify.risk.frontend.model.TestCase; import java.util.Collection; import java.util.List; /** * View the details of a Capability, including attached data artifacts. * * @author jimr@google.com (Jim Reardon) */ public class CapabilityDetailsViewImpl extends Composite implements CapabilityDetailsView { private static final String HEADER_TEXT = "Details for Capability: "; /** * Used to wire parent class to associated UI Binder. */ interface CapabilityDetailsViewImplUiBinder extends UiBinder<Widget, CapabilityDetailsViewImpl> {} private static final CapabilityDetailsViewImplUiBinder uiBinder = GWT.create(CapabilityDetailsViewImplUiBinder.class); @UiField public PageSectionVerticalPanel detailsSection; @UiField public CheckBox signoffBox; @UiField public Image testChart; @UiField public Grid testGrid; @UiField public HTML testNotRunCount; @UiField public HTML testPassedCount; @UiField public HTML testFailedCount; @UiField public Grid bugGrid; @UiField public Grid changeGrid; // Will be constructed and added to the above panel once we know what capability we're showing. public EditCapabilityWidget capabilityWidget; boolean isEditable = false; private CapabilityDetailsView.Presenter presenter; // TODO(jimr): Reconsider this data model. Keeping each data item stored twice is not awesome. private List<Attribute> attributes; private List<Component> components; private List<Bug> bugs; private List<Bug> otherBugs = Lists.newArrayList(); private List<Bug> capabilityBugs = Lists.newArrayList(); private List<TestCase> tests; private List<TestCase> otherTests = Lists.newArrayList(); private List<TestCase> capabilityTests = Lists.newArrayList(); private List<Checkin> checkins; private List<Checkin> otherCheckins = Lists.newArrayList(); private List<Checkin> capabilityCheckins = Lists.newArrayList(); private Collection<String> projectLabels = Lists.newArrayList(); private Anchor addBugAnchor; private Anchor addCheckinAnchor; private Anchor addTestAnchor; private Capability capability = null; public CapabilityDetailsViewImpl() { initWidget(uiBinder.createAndBindUi(this)); detailsSection.setHeaderText(HEADER_TEXT); } @UiHandler("signoffBox") public void addSignoffClickHandler(ClickEvent click) { presenter.setSignoff(capability.getCapabilityId(), signoffBox.getValue()); } @Override public Widget asWidget() { return this; } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; refresh(); } @Override public void setCapability(Capability capability) { this.capability = capability; refresh(); } @Override public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; refresh(); } @Override public void setBugs(List<Bug> bugs) { this.bugs = bugs; refresh(); } @Override public void setCheckins(List<Checkin> checkins) { this.checkins = checkins; refresh(); } @Override public void setProjectLabels(Collection<String> labels) { projectLabels.clear(); projectLabels.addAll(labels); if (capabilityWidget != null) { capabilityWidget.setLabelSuggestions(labels); } } private <T extends UploadedDatum> void splitData(List<T> inItems, List<T> otherItems, List<T> capabilityItems) { otherItems.clear(); capabilityItems.clear(); for (T item : inItems) { if (capability.getCapabilityId().equals(item.getTargetCapabilityId())) { capabilityItems.add(item); } else { otherItems.add(item); } } } @Override public void setTests(List<TestCase> tests) { this.tests = tests; refresh(); } @Override public void setComponents(List<Component> components) { this.components = components; refresh(); } @SuppressWarnings("unchecked") @Override public void refresh() { // Don't re-draw until all data has successfully loaded. if (attributes != null && components != null && capability != null && bugs != null && tests != null && checkins != null) { splitData(tests, otherTests, capabilityTests); splitData(bugs, otherBugs, capabilityBugs); splitData(checkins, otherCheckins, capabilityCheckins); capabilityWidget = new EditCapabilityWidget(capability); capabilityWidget.setLabelSuggestions(projectLabels); capabilityWidget.setAttributes(attributes); capabilityWidget.setComponents(components); capabilityWidget.disableDelete(); if (isEditable) { capabilityWidget.makeEditable(); } capabilityWidget.expand(); capabilityWidget.addValueChangeHandler(new ValueChangeHandler<Capability>() { @Override public void onValueChange(ValueChangeEvent<Capability> event) { capability = event.getValue(); presenter.updateCapability(capability); refresh(); capabilityWidget.showSaved(); } }); detailsSection.clear(); detailsSection.add(capabilityWidget); updateTestSection(); updateBugSection(); updateCheckinsSection(); detailsSection.setHeaderText(HEADER_TEXT + capability.getName()); } } @Override public void makeEditable() { isEditable = true; signoffBox.setEnabled(true); if (capabilityWidget != null) { capabilityWidget.makeEditable(); } if (addTestAnchor != null) { addTestAnchor.setVisible(true); } if (addBugAnchor != null) { addBugAnchor.setVisible(true); } if (addCheckinAnchor != null) { addCheckinAnchor.setVisible(true); } } @Override public void reset() { attributes = null; components = null; capabilityWidget = null; capability = null; bugs = null; tests = null; checkins = null; } private TestCase getTestCaseById(long id) { for (TestCase test : tests) { if (test.getInternalId() == id) { return test; } } return null; } private Widget buildTestHeaderWidget(String header, String addText) { final ListBox options = new ListBox(); for (TestCase test : otherTests) { options.addItem(test.getExternalId() + " " + test.getTitle(), String.valueOf(test.getInternalId())); } VerticalPanel addForm = new VerticalPanel(); addForm.add(options); final DisclosurePanel disclosure = new DisclosurePanel(); Button button = new Button(" Add ", new ClickHandler() { @Override public void onClick(ClickEvent event) { long id = Long.parseLong((options.getValue(options.getSelectedIndex()))); presenter.assignTestCaseToCapability(capability.getCapabilityId(), id); disclosure.setOpen(false); TestCase test = getTestCaseById(id); test.setTargetCapabilityId(capability.getCapabilityId()); refresh(); } }); addForm.add(button); disclosure.setAnimationEnabled(true); disclosure.setOpen(false); disclosure.setContent(addForm); HorizontalPanel title = new HorizontalPanel(); title.add(new Label(header)); addTestAnchor = new Anchor(addText); addTestAnchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { disclosure.setOpen(!disclosure.isOpen()); } }); addTestAnchor.setVisible(isEditable); title.add(addTestAnchor); VerticalPanel everything = new VerticalPanel(); everything.add(title); everything.add(disclosure); return everything; } private void updateTestSection() { testGrid.setTitle("Recent Test Activity"); testGrid.resize(capabilityTests.size() + 1, 1); testGrid.setWidget(0, 0, buildTestHeaderWidget("Recent Test Activity", "add test")); int passed = 0, failed = 0, notRun = 0; for (int i = 0; i < capabilityTests.size(); i++) { TestCase test = capabilityTests.get(i); HorizontalPanel panel = new HorizontalPanel(); panel.add(getTestStateImage(test.getState())); Anchor anchor = new Anchor(test.getLinkText(), test.getLinkUrl()); anchor.setTarget("_blank"); panel.add(anchor); Label statusLabel = new Label(); int state = getTestState(test.getState()); if (state < 0) { statusLabel.setText(" - failed " + getDateText(test.getStateDate())); failed++; } else if (state > 0) { statusLabel.setText(" - passed " + getDateText(test.getStateDate())); passed++; } else { statusLabel.setText(" - no result"); notRun++; } panel.add(statusLabel); testGrid.setWidget(i + 1, 0, panel); } testNotRunCount.setHTML("not run <b>" + notRun + "</b>"); testPassedCount.setHTML("passed <b>" + passed + "</b>"); testFailedCount.setHTML("failed <b>" + failed + "</b>"); String imageUrl = getTestChartUrl(passed, failed, notRun); if (imageUrl == null || "".equals(imageUrl)) { testChart.setVisible(false); } else { testChart.setUrl(imageUrl); testChart.setVisible(true); } } private Bug getBugById(long id) { for (Bug bug : bugs) { if (bug.getInternalId() == id) { return bug; } } return null; } private Widget buildBugHeaderWidget(String header, String addText) { final ListBox options = new ListBox(); for (Bug bug : otherBugs) { options.addItem(bug.getExternalId() + " " + bug.getTitle(), String.valueOf(bug.getInternalId())); } VerticalPanel addForm = new VerticalPanel(); addForm.add(options); final DisclosurePanel disclosure = new DisclosurePanel(); Button button = new Button(" Add ", new ClickHandler() { @Override public void onClick(ClickEvent event) { long id = Long.parseLong((options.getValue(options.getSelectedIndex()))); presenter.assignBugToCapability(capability.getCapabilityId(), id); disclosure.setOpen(false); Bug bug = getBugById(id); bug.setTargetCapabilityId(capability.getCapabilityId()); refresh(); } }); addForm.add(button); disclosure.setAnimationEnabled(true); disclosure.setOpen(false); disclosure.setContent(addForm); HorizontalPanel title = new HorizontalPanel(); title.add(new Label(header)); addBugAnchor = new Anchor(addText); addBugAnchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { disclosure.setOpen(!disclosure.isOpen()); } }); addBugAnchor.setVisible(isEditable); title.add(addBugAnchor); VerticalPanel everything = new VerticalPanel(); everything.add(title); everything.add(disclosure); return everything; } private void updateBugSection() { bugGrid.resize(capabilityBugs.size() + 1, 1); bugGrid.setTitle("Bugs (" + capabilityBugs.size() + " total)"); bugGrid.setWidget(0, 0, buildBugHeaderWidget("Bugs (" + capabilityBugs.size() + " total)", "add bug")); for (int i = 0; i < capabilityBugs.size(); i++) { Bug bug = capabilityBugs.get(i); HorizontalPanel panel = new HorizontalPanel(); panel.add(getBugStateImage(bug.getState())); Anchor anchor = new Anchor(bug.getLinkText(), bug.getLinkUrl()); anchor.setTarget("_blank"); panel.add(anchor); Label statusLabel = new Label(); statusLabel.setText(" - filed " + getDateText(bug.getStateDate())); panel.add(statusLabel); bugGrid.setWidget(i + 1, 0, panel); } } private Checkin getCheckinById(long id) { for (Checkin checkin : checkins) { if (checkin.getInternalId() == id) { return checkin; } } return null; } private Widget buildCheckinHeaderWidget(String header, String addText) { final ListBox options = new ListBox(); for (Checkin checkin : otherCheckins) { options.addItem(checkin.getExternalId() + " " + checkin.getSummary(), String.valueOf(checkin.getInternalId())); } VerticalPanel addForm = new VerticalPanel(); addForm.add(options); final DisclosurePanel disclosure = new DisclosurePanel(); Button button = new Button(" Add ", new ClickHandler() { @Override public void onClick(ClickEvent event) { long id = Long.parseLong((options.getValue(options.getSelectedIndex()))); presenter.assignCheckinToCapability(capability.getCapabilityId(), id); disclosure.setOpen(false); Checkin checkin = getCheckinById(id); checkin.setTargetCapabilityId(capability.getCapabilityId()); refresh(); } }); addForm.add(button); disclosure.setAnimationEnabled(true); disclosure.setOpen(false); disclosure.setContent(addForm); HorizontalPanel title = new HorizontalPanel(); title.add(new Label(header)); addCheckinAnchor = new Anchor(addText); addCheckinAnchor.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { disclosure.setOpen(!disclosure.isOpen()); } }); addCheckinAnchor.setVisible(isEditable); title.add(addCheckinAnchor); VerticalPanel everything = new VerticalPanel(); everything.add(title); everything.add(disclosure); return everything; } private void updateCheckinsSection() { changeGrid.setTitle("Recent Code Changes (" + capabilityCheckins.size() + " total)"); changeGrid.resize(capabilityCheckins.size() + 1, 1); changeGrid.setWidget(0, 0, buildCheckinHeaderWidget( "Recent Code Changes (" + capabilityCheckins.size() + " total)", "add code change")); for (int i = 0; i < capabilityCheckins.size(); i++) { Checkin checkin = capabilityCheckins.get(i); HorizontalPanel panel = new HorizontalPanel(); panel.add(new Image("/images/teststate-passed.png")); Anchor anchor = new Anchor(checkin.getLinkText(), checkin.getLinkUrl()); anchor.setTarget("_blank"); panel.add(anchor); Label statusLabel = new Label(); statusLabel.setText(" - submitted " + getDateText(checkin.getStateDate())); panel.add(statusLabel); changeGrid.setWidget(i + 1, 0, panel); } } private Image getBugStateImage(String state) { Image image = new Image(); if (state != null && state.toLowerCase().equals("closed")) { image.setUrl("/images/bugstate-closed.png"); } else { image.setUrl("/images/bugstate-active.png"); } return image; } /** * Turns a number of days, eg: 3, into a string like "3 days ago" or "1 day ago" or "today". * @param date date reported/filed/etc. * @return string representation. */ private String getDateText(Long date) { int days = -1; if (date != null && date > 0) { days = (int) ((double) System.currentTimeMillis() - date) / 86400000; } if (days == 0) { return "today"; } else if (days == 1) { return "1 day ago"; } else if (days > 1) { return days + " days ago"; } return ""; } /** * Determine from a text description what state a test is in. * * @param state the text state. * @return -1 for failing test, 0 for unsure/not run, 1 for passing. */ private int getTestState(String state) { if (state == null) { return 0; } state = state.toLowerCase(); if (state.startsWith("pass")) { return 1; } else if (state.startsWith("fail")) { return -1; } else { return 0; } } private Image getTestStateImage(String state) { Image image = new Image(); int stateVal = getTestState(state); if (stateVal > 0) { image.setUrl("/images/teststate-passed.png"); } else if (stateVal < 0) { image.setUrl("/images/teststate-failed.png"); } else { image.setUrl("/images/teststate-notrun.png"); } return image; } private String getTestChartUrl(int passed, int failed, int notRun) { int total = passed + failed + notRun; if (total < 1) { return null; } passed = passed * 100 / total; failed = failed * 100 / total; notRun = notRun * 100 / total; String pStr = String.valueOf(passed); String fStr = String.valueOf(failed); String nStr = String.valueOf(notRun); return "http://chart.apis.google.com/chart?chs=500x20&cht=bhs&chco=FFFFFF,008000,FF0000&chd=t:" + nStr + "|" + pStr + "|" + fStr; } @Override public void setSignoff(boolean signoff) { signoffBox.setValue(signoff); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/CapabilityDetailsViewImpl.java
Java
asf20
19,099
// 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.client.view.impl; import com.google.common.collect.Maps; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.presenter.DataRequestPresenter; import com.google.testing.testify.risk.frontend.client.view.ConfigureDataView; import com.google.testing.testify.risk.frontend.client.view.DataRequestView; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import java.util.List; import java.util.Map; /** * A widget for configuring a project's data sources. * * @author chrsmith@google.com (Chris Smith) */ public class ConfigureDataViewImpl extends Composite implements ConfigureDataView { interface ConfigureDataViewImplUiBinder extends UiBinder<Widget, ConfigureDataViewImpl> {} private static final ConfigureDataViewImplUiBinder uiBinder = GWT.create(ConfigureDataViewImplUiBinder.class); @UiField public ListBox standardDataSourcesListBox; @UiField public TextBox dataSourceTextBox; @UiField public Button addDataRequestButton; @UiField public VerticalPanel dataRequestsPanel; private List<DataRequest> dataRequests = null; private Map<String, DataSource> dataSources = null; private Presenter presenter; /** * Constructs a ConfigureDataView object. */ public ConfigureDataViewImpl() { initWidget(uiBinder.createAndBindUi(this)); dataSourceTextBox.getElement().setAttribute("placeholder", "Name this data source..."); } @UiHandler("standardDataSourcesListBox") public void handleStandardDataSourcesListBoxChanged(ChangeEvent event) { DataSource source = getSelectedSource(); // If this source doesn't have any defined options, it's our "Other..." source which means // we need them to input the name they want. dataSourceTextBox.setVisible(source.getParameters().size() < 1); } private DataSource getSelectedSource() { int dataSourceIndex = standardDataSourcesListBox.getSelectedIndex(); String selectedSourceName = standardDataSourcesListBox.getItemText(dataSourceIndex); return dataSources.get(selectedSourceName); } @UiHandler("addDataRequestButton") public void handleAddDataRequestButtonClicked(ClickEvent event) { if (presenter != null) { DataSource source = getSelectedSource(); if (source != null) { DataRequest newRequest = new DataRequest(); newRequest.setDataSourceName(source.getName()); if (source.getParameters().size() < 1) { newRequest.setCustomName(dataSourceTextBox.getText()); } presenter.addDataRequest(newRequest); } } } /** * Binds this View to the given Presenter. */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public void setDataRequests(List<DataRequest> dataRequests) { this.dataRequests = dataRequests; updateDataRequests(); } @Override public void setDataSources(List<DataSource> dataSources) { this.dataSources = Maps.newHashMap(); standardDataSourcesListBox.clear(); for (DataSource dataSource : dataSources) { this.dataSources.put(dataSource.getName(), dataSource); standardDataSourcesListBox.addItem(dataSource.getName()); } updateDataRequests(); } private void updateDataRequests() { // We need both DataRequests and DataSources to be populated before doing this, so wait for // both to be non-null. if (dataSources != null && dataRequests != null) { dataRequestsPanel.clear(); for (DataRequest request : dataRequests) { DataRequestView view = new DataRequestViewImpl(); DataRequestPresenter presenter = new DataRequestPresenter(request, dataSources.get(request.getDataSourceName()), view, this.presenter); dataRequestsPanel.add(view.asWidget()); } } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ConfigureDataViewImpl.java
Java
asf20
5,093
// 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.client.view.impl; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextArea; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; import com.google.testing.testify.risk.frontend.client.view.AttributeView; import com.google.testing.testify.risk.frontend.client.view.widgets.EditableLabel; import com.google.testing.testify.risk.frontend.client.view.widgets.LabelWidget; import com.google.testing.testify.risk.frontend.model.AccLabel; import java.util.Collection; import java.util.List; // TODO(chrsmith): Merge ComponentViewImpl and AttributeViewImpl into a single widget. /** * Widget for displaying an Attribute. * * @author chrsmith@google.com (Chris Smith) */ public class AttributeViewImpl extends Composite implements AttributeView { /** * Used to wire parent class to associated UI Binder. */ interface AttributeViewImplUiBinder extends UiBinder<Widget, AttributeViewImpl> { } private static final AttributeViewImplUiBinder uiBinder = GWT.create(AttributeViewImplUiBinder.class); @UiField protected Label attributeGripper; @UiField protected EditableLabel attributeName; @UiField protected TextArea description; @UiField protected Label attributeId; @UiField protected Image deleteAttributeImage; @UiField protected FlowPanel labelsPanel; @UiField protected CheckBox signoffBox; private LabelWidget addLabelWidget; private boolean editingEnabled = false; /** Presenter associated with this View */ private Presenter presenter; private final Collection<String> labelSuggestions = Lists.newArrayList(); public AttributeViewImpl() { initWidget(uiBinder.createAndBindUi(this)); description.getElement().setAttribute("placeholder", "Enter description of this attribute..."); } @UiHandler("signoffBox") protected void onSignoffClicked(ClickEvent event) { presenter.updateSignoff(signoffBox.getValue()); } @UiHandler("description") protected void onDescriptionChange(ChangeEvent event) { presenter.onDescriptionEdited(description.getText()); } /** Wires renaming the Attribute in the UI to the backing presenter. */ @UiHandler("attributeName") protected void onAttributeNameChanged(ValueChangeEvent<String> event) { if (presenter != null) { if (event.getValue().length() == 0) { NotificationUtil.displayErrorMessage("Invalid name for Attribute."); presenter.refreshView(); } else { presenter.onRename(event.getValue()); } } } /** * Handler for the deleteComponentButton's click event, removing the Component. */ @UiHandler("deleteAttributeImage") protected void onDeleteAttributeImageClicked(ClickEvent event) { String promptText = "Are you sure you want to remove " + attributeName.getText() + "?"; if (Window.confirm(promptText)) { presenter.onRemove(); } } /** * Updates the label suggestions for all labels on this view. */ public void setLabelSuggestions(Collection<String> labelSuggestions) { this.labelSuggestions.clear(); this.labelSuggestions.addAll(labelSuggestions); for (Widget w : labelsPanel) { if (w instanceof LabelWidget) { LabelWidget l = (LabelWidget) w; l.setLabelSuggestions(this.labelSuggestions); } } } /** * Displays a new Component Label on this Widget. */ public void displayLabel(final AccLabel label) { final LabelWidget labelWidget = new LabelWidget(label.getLabelText()); labelWidget.setLabelSuggestions(labelSuggestions); labelWidget.setEditable(editingEnabled); labelWidget.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { if (event.getValue() == null) { labelsPanel.remove(labelWidget); presenter.onRemoveLabel(label); } else { presenter.onUpdateLabel(label, event.getValue()); } } }); labelsPanel.add(labelWidget); } /** Updates the Widget's list of regular labels. */ @Override public void setLabels(List<AccLabel> labels) { labelsPanel.clear(); for (AccLabel label : labels) { displayLabel(label); } addBlankLabel(); } private void addBlankLabel() { final String newText = "new label"; addLabelWidget = new LabelWidget(newText, true); addLabelWidget.setLabelSuggestions(labelSuggestions); addLabelWidget.setVisible(editingEnabled); addLabelWidget.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { presenter.onAddLabel(event.getValue()); labelsPanel.remove(addLabelWidget); addBlankLabel(); } }); addLabelWidget.setEditable(true); labelsPanel.add(addLabelWidget); } @Override public Widget asWidget() { return this; } /** * Hides this widget, equivalent to setVisible(false). */ @Override public void hide() { setVisible(false); } /** * Binds this View to a given Presenter for two-way communication. */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } /** * Sets the UI to display the Attribute's name. */ @Override public void setAttributeName(String name) { if (name != null) { attributeName.setText(name); } } /** * Sets the UI to display the Attribute's ID. */ @Override public void setAttributeId(Long id) { if (id != null) { attributeId.setText(id.toString()); } } @Override public void enableEditing() { editingEnabled = true; attributeGripper.setVisible(true); signoffBox.setEnabled(true); attributeName.setReadOnly(false); deleteAttributeImage.setVisible(true); description.setEnabled(true); for (Widget widget : labelsPanel) { LabelWidget label = (LabelWidget) widget; label.setEditable(true); } if (addLabelWidget != null) { addLabelWidget.setVisible(true); } } @Override public void setSignedOff(boolean signedOff) { signoffBox.setValue(signedOff); } /** Returns the ID of the underlying Attribute if applicable. Otherwise returns -1. */ public long getAttributeId() { try { return Long.parseLong(attributeId.getText()); } catch (NumberFormatException nfe) { return -1; } } @Override public void setDescription(String description) { this.description.setText(description == null ? "" : description); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/AttributeViewImpl.java
Java
asf20
8,018
// 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.client.view.impl; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ChangeHandler; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.view.DataRequestView; import com.google.testing.testify.risk.frontend.client.view.widgets.ConstrainedParameterWidget; import com.google.testing.testify.risk.frontend.client.view.widgets.CustomParameterWidget; import com.google.testing.testify.risk.frontend.client.view.widgets.DataRequestParameterWidget; import com.google.testing.testify.risk.frontend.model.DataRequestOption; import java.util.List; // TODO(chrsmith): Provide a readonly mode for non-editor users. /** * Widget for displaying a DataRequest. * * @author chrsmith@google.com (Chris Smith) */ public class DataRequestViewImpl extends Composite implements DataRequestView { /** Wire parent class to associated UI Binder. */ interface DataRequestViewImplUiBinder extends UiBinder<Widget, DataRequestViewImpl> {} private static final DataRequestViewImplUiBinder uiBinder = GWT.create(DataRequestViewImplUiBinder.class); @UiField protected Label dataRequestSourceName; @UiField protected VerticalPanel dataRequestParameters; @UiField protected Anchor addParameterLink; @UiField protected Button updateDataRequest; @UiField protected Button cancelUpdateDataRequest; @UiField protected Image deleteDataRequestImage; /** List of allowable values for a parameter key. null if arbitrary keys allowed. */ private final List<String> parameterKeyConstraint = Lists.newArrayList(); /** Presenter associated with this View */ private Presenter presenter; public DataRequestViewImpl() { initWidget(uiBinder.createAndBindUi(this)); } /** When the user clicks the 'add parameter' link, add a new parameter to the end of the list. */ @UiHandler("addParameterLink") protected void handleAddParameterLinkClick(ClickEvent event) { dataRequestParameters.add((Widget) createRequestWidget("", "")); } @UiHandler("updateDataRequest") void onUpdateDataRequestClicked(ClickEvent event) { // Gather up all parameters and notify the presenter. List<DataRequestOption> newOptions = Lists.newArrayList(); for (Widget widget : dataRequestParameters) { DataRequestParameterWidget parameterWidget = (DataRequestParameterWidget) widget; newOptions.add(new DataRequestOption(parameterWidget.getParameterKey(), parameterWidget.getParameterValue())); } presenter.onUpdate(newOptions); } @UiHandler("cancelUpdateDataRequest") void onCancelUpdateDataRequestClicked(ClickEvent event) { presenter.refreshView(); } /** * Handler for the deleteComponentImage's click event, removing the Component. */ @UiHandler("deleteDataRequestImage") void onDeleteComponentImageClicked(ClickEvent event) { String promptText = "Are you sure you want to remove this data request?"; if (Window.confirm(promptText)) { presenter.onRemove(); } } /** * Initialize this View's Presenter object. (For two-way communication.) */ @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public Widget asWidget() { return this; } /** * Hides the given Widget, equivalent to setVisible(false). */ @Override public void hide() { this.setVisible(false); } @Override public void setDataSourceName(String dataSourceName) { dataRequestSourceName.setText(dataSourceName); } private DataRequestParameterWidget createRequestWidget(String name, String value) { final DataRequestParameterWidget param; if (parameterKeyConstraint != null) { param = new ConstrainedParameterWidget(parameterKeyConstraint, name, value); } else { param = new CustomParameterWidget(name, value); } param.addChangeHandler(new ChangeHandler() { @Override public void onChange(ChangeEvent arg0) { Widget w = (Widget) param; dataRequestParameters.remove(w); } }); return param; } @Override public void setDataSourceParameters(List<String> keyValues, List<DataRequestOption> options) { parameterKeyConstraint.clear(); parameterKeyConstraint.addAll(keyValues); dataRequestParameters.clear(); for (DataRequestOption option : options) { dataRequestParameters.add((Widget) createRequestWidget(option.getName(), option.getValue())); } // If there are no parameters already, add a blank line to encourage them to add some. if (options.size() < 1) { handleAddParameterLinkClick(null); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/DataRequestViewImpl.java
Java
asf20
5,949
// 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.client.view.impl; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedEvent; import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedHandler; import com.google.testing.testify.risk.frontend.client.view.CapabilitiesView; import com.google.testing.testify.risk.frontend.client.view.widgets.CapabilitiesGridWidget; import com.google.testing.testify.risk.frontend.client.view.widgets.EasyDisclosurePanel; import com.google.testing.testify.risk.frontend.client.view.widgets.EditCapabilityWidget; import com.google.testing.testify.risk.frontend.client.view.widgets.SortableVerticalPanel; 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.Pair; import java.util.Collection; import java.util.List; /** * Generic view on top of a Project's Capabilities. Note that this View has two alternate View * methods (List and Grid) both wired to the same Model, View, Presenter setup. * * @author chrsmith@google.com (Chris Smith) */ public class CapabilitiesViewImpl extends Composite implements CapabilitiesView { private static final String HEADER_TEXT = "Capabilities by Attribute and Component"; /** * Used to wire parent class to associated UI Binder. */ interface CapabilitiesViewImplUiBinder extends UiBinder<Widget, CapabilitiesViewImpl> {} private static final CapabilitiesViewImplUiBinder uiBinder = GWT.create(CapabilitiesViewImplUiBinder.class); @UiField public CapabilitiesGridWidget capabilitiesGrid; @UiField public VerticalPanel capabilitiesContainer; @UiField public Label capabilitiesContainerTitle; @UiField public HorizontalPanel addNewCapabilityPanel; @UiField public TextBox newCapabilityName; @UiField public Button addNewCapabilityButton; @UiField public SortableVerticalPanel<EditCapabilityWidget> capabilitiesPanel; private List<Capability> capabilities; private List<Component> components; private List<Attribute> attributes; private final Collection<String> projectLabels = Lists.newArrayList(); private Pair<Component, Attribute> selectedIntersection; private boolean isEditable = false; private Presenter presenter; /** * Constructs a CapabilitiesViewImpl object. */ public CapabilitiesViewImpl() { initWidget(uiBinder.createAndBindUi(this)); capabilitiesGrid.addValueChangeHandler(new ValueChangeHandler<Pair<Component,Attribute>>() { @Override public void onValueChange(ValueChangeEvent<Pair<Component, Attribute>> event) { selectedIntersection = event.getValue(); newCapabilityName.setText(""); tryToPopulateCapabilitiesPanel(); } }); capabilitiesPanel.addWidgetsReorderedHandler( new WidgetsReorderedHandler() { @Override public void onWidgetsReordered(WidgetsReorderedEvent event) { if (presenter != null) { List<Long> ids = Lists.newArrayList(); for (Widget w : event.getWidgetOrdering()) { ids.add(((EditCapabilityWidget) w).getCapabilityId()); } presenter.reorderCapabilities(ids); } } }); newCapabilityName.getElement().setAttribute("placeholder", "Add new capability..."); } @UiFactory public EasyDisclosurePanel createDisclosurePanel() { Label header = new Label(HEADER_TEXT); header.addStyleName("tty-DisclosureHeader"); return new EasyDisclosurePanel(header); } /** * Handler for hitting enter in the new capability text box. */ @UiHandler("newCapabilityName") void onComponentNameEnter(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { addNewCapabilityButton.click(); } } @UiHandler("addNewCapabilityButton") protected void handleNewButton(ClickEvent e) { String name = newCapabilityName.getText().trim(); if (name.length() == 0) { Window.alert("Please enter a name for the capability."); return; } long cId = selectedIntersection.getFirst().getComponentId(); long aId = selectedIntersection.getSecond().getAttributeId(); long pId = selectedIntersection.getSecond().getParentProjectId(); Capability c = new Capability(pId, aId, cId); c.setName(name); presenter.onAddCapability(c); newCapabilityName.setText(""); } @Override public Widget asWidget() { return this; } @Override public void setPresenter(Presenter presenter) { this.presenter = presenter; } @Override public void setCapabilities(List<Capability> capabilities) { this.capabilities = capabilities; capabilitiesGrid.setCapabilities(capabilities); tryToPopulateCapabilitiesPanel(); } @Override public void setAttributes(List<Attribute> attributes) { this.attributes = attributes; capabilitiesGrid.setAttributes(attributes); tryToPopulateCapabilitiesPanel(); } @Override public void setComponents(List<Component> components) { this.components = components; capabilitiesGrid.setComponents(components); tryToPopulateCapabilitiesPanel(); } @Override public void setProjectLabels(Collection<String> labels) { projectLabels.clear(); projectLabels.addAll(labels); for (Widget w : capabilitiesContainer) { EditCapabilityWidget capabilityWidget = (EditCapabilityWidget) w; capabilityWidget.setLabelSuggestions(projectLabels); } } private void updateCapability(Capability capability) { presenter.onUpdateCapability(capability); capabilitiesGrid.updateCapability(capability); tryToPopulateCapabilitiesPanel(); } private void removeCapability(Capability capability) { presenter.onRemoveCapability(capability); capabilitiesGrid.deleteCapability(capability); capabilities.remove(capability); tryToPopulateCapabilitiesPanel(); } /** * Populates the capabilities panel with capabilities widgets. This requires data already be * loaded, so it will not show the panel if all data has not been loaded. */ private void tryToPopulateCapabilitiesPanel() { if (selectedIntersection != null && attributes != null && components != null && capabilities != null) { Component component = selectedIntersection.getFirst(); Attribute attribute = selectedIntersection.getSecond(); capabilitiesContainer.setVisible(true); capabilitiesContainerTitle.setText(component.getName() + " is " + attribute.getName()); List<EditCapabilityWidget> widgets = Lists.newArrayList(); for (final Capability capability : capabilities) { // If we're interested in this capability (it matches our current filter). if (capability.getComponentId() == component.getComponentId() && capability.getAttributeId() == attribute.getAttributeId()) { // Create and populate a capability widget for this capability. final EditCapabilityWidget widget = new EditCapabilityWidget(capability); widget.addValueChangeHandler(new ValueChangeHandler<Capability>() { @Override public void onValueChange(ValueChangeEvent<Capability> event) { if (event.getValue() == null) { // Since the value is null, we'll just use the old value to grab the ID. removeCapability(capability); } else { updateCapability(event.getValue()); widget.showSaved(); } } }); widget.setComponents(components); widget.setAttributes(attributes); widget.setLabelSuggestions(projectLabels); if (isEditable) { widget.makeEditable(); } widgets.add(widget); } } capabilitiesPanel.setWidgets(widgets, new Function<EditCapabilityWidget, Widget>() { @Override public Widget apply(EditCapabilityWidget input) { return input.getCapabilityGripper(); } }); } else { capabilitiesContainer.setVisible(false); } } @Override public void setEditable(boolean isEditable) { this.isEditable = isEditable; for (Widget w : capabilitiesPanel) { if (isEditable) { ((EditCapabilityWidget) w).makeEditable(); } } addNewCapabilityPanel.setVisible(isEditable); } @Override public void addCapability(Capability capability) { capabilitiesGrid.addCapability(capability); // Insert at top. capabilities.add(0, capability); // TODO (jimr): instead of a full refresh, we should just pop the new widget // on top. However, the sortable panel doesn't really handle adding a single // widget, so a full refresh is the path of least resistance currently. tryToPopulateCapabilitiesPanel(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/CapabilitiesViewImpl.java
Java
asf20
10,643
// 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.client.view.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.util.LinkUtil; import com.google.testing.testify.risk.frontend.client.view.widgets.PageSectionVerticalPanel; import com.google.testing.testify.risk.frontend.model.UploadedDatum; import java.util.List; /** * Page for displaying data uploaded into a project. * * @author chrsmith@google.com (Chris Smith) */ public class ProjectDataViewImpl extends Composite { interface ProjectDataViewImplUiBinder extends UiBinder<Widget, ProjectDataViewImpl> {} private static final ProjectDataViewImplUiBinder uiBinder = GWT.create(ProjectDataViewImplUiBinder.class); @UiField public PageSectionVerticalPanel pageSection; @UiField public InlineLabel introText; @UiField public Grid dataGrid; @UiField public Label dataSummary; private static final String GRID_CELL_CSS_STYLE = "tty-DataGridCell"; private static final String GRID_IMAGE_CELL_CSS_STYLE = "tty-DataGridImageCell"; private static final String GRID_HEADER_CSS_STYLE = "tty-DataGridHeaderCell"; public ProjectDataViewImpl() { initWidget(uiBinder.createAndBindUi(this)); dataSummary.setText("No data provided yet."); } /** Sets the page header and intro text. */ public void setPageText(String headerText, String introText) { pageSection.setHeaderText(headerText); this.introText.setText(introText); } public void displayData(List<UploadedDatum> data) { if (data.size() == 0) { dataSummary.setText("No items have been uploaded."); return; } UploadedDatum firstItem = data.get(0); dataSummary.setText( "Showing " + Integer.toString(data.size()) + " " + firstItem.getDatumType().getPlural()); dataGrid.clear(); // Header row + one for each bug x datum, Attribute, Component, Capability dataGrid.resize(data.size() + 1, 4); // Set grid headers. dataGrid.setWidget(0, 0, new Label(firstItem.getDatumType().getPlural())); dataGrid.setWidget(0, 1, new Label("Attribute")); dataGrid.setWidget(0, 2, new Label("Component")); dataGrid.setWidget(0, 3, new Label("Capability")); dataGrid.getWidget(0, 0).addStyleName(GRID_HEADER_CSS_STYLE); dataGrid.getWidget(0, 1).addStyleName(GRID_HEADER_CSS_STYLE); dataGrid.getWidget(0, 2).addStyleName(GRID_HEADER_CSS_STYLE); dataGrid.getWidget(0, 3).addStyleName(GRID_HEADER_CSS_STYLE); // Fill with data. for (int i = 0; i < data.size(); i++) { UploadedDatum datum = data.get(i); String host = LinkUtil.getLinkHost(datum.getLinkUrl()); Widget description; if (host != null) { HorizontalPanel panel = new HorizontalPanel(); Anchor anchor = new Anchor(datum.getLinkText(), datum.getLinkUrl()); anchor.setTarget("_blank"); Label hostLabel = new Label(host); panel.add(anchor); panel.add(hostLabel); description = panel; } else { description = new Label(datum.getLinkText() + " [" + datum.getLinkUrl() + "]"); } description.addStyleName(GRID_CELL_CSS_STYLE); description.setTitle(datum.getToolTip()); dataGrid.setWidget(i + 1, 0, description); // Display images indicating whether or not the datum is associated with project artifacts. // For example, a Bug may be associated with a Component or a Testcase might validate scenarios // for a given Attribute. The user can associate data with project artifacts using SuperLabels. dataGrid.setWidget(i + 1, 1, (datum.isAttachedToAttribute()) ? getX() : getCheckmark()); dataGrid.setWidget(i + 1, 2, (datum.isAttachedToComponent()) ? getX() : getCheckmark()); dataGrid.setWidget(i + 1, 3, (datum.isAttachedToCapability()) ? getX() : getCheckmark()); } } /** Returns an X image for the dataGrid. */ private Image getX() { Image redXImage = new Image("/images/redx_12.png"); redXImage.addStyleName(GRID_IMAGE_CELL_CSS_STYLE); return redXImage; } /** Returns a checkmark image for the dataGrid. */ private Image getCheckmark() { Image checkImage = new Image("/images/checkmark_12.png"); checkImage.addStyleName(GRID_IMAGE_CELL_CSS_STYLE); return checkImage; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/impl/ProjectDataViewImpl.java
Java
asf20
5,318
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Filter; import java.util.List; import java.util.Map; /** * View on top of a page to configure filters. * * @author jimr@google.com (Jim Reardon) */ public interface ConfigureFiltersView { /** * Interface for notifying the Presenter about events going down in the view. */ public interface Presenter { void addFilter(Filter newFilter); void updateFilter(Filter filterToUpdate); void deleteFilter(Filter filterToDelete); } void setFilters(List<Filter> filters); void setAttributes(Map<String, Long> attributes); void setComponents(Map<String, Long> components); void setCapabilities(Map<String, Long> capabilities); void setPresenter(Presenter presenter); Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/ConfigureFiltersView.java
Java
asf20
1,497
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import java.util.List; /** * View on top of a page for configuring project data sources. * * @author chrsmith@google.com (Chris Smith) */ public interface ConfigureDataView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * Adds a new data request. */ void addDataRequest(DataRequest newRequest); /** * Update an existing data request. */ void updateDataRequest(DataRequest requestToUpdate); /** * Removes a data request */ void deleteDataRequest(DataRequest requestToDelete); } /** * Sets the list of enabled data providers. */ void setDataRequests(List<DataRequest> dataRequests); /** * Provide the list of data sources. */ void setDataSources(List<DataSource> dataSources); /** * Bind the view and the underlying presenter it communicates with. */ void setPresenter(Presenter presenter); /** * Converts the view into a GWT widget. */ Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/ConfigureDataView.java
Java
asf20
1,897
// 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.client.view; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import java.util.Collection; import java.util.List; /** * View on top of the Components page. * * @author chrsmith@google.com (Chris Smith) */ public interface ComponentsView { /** * Interface for notifying the Presenter about events arising from the View. */ public interface Presenter { /** * @return a handle to the Presenter's ProjectService serverlet. Ideally this should be hidden. */ ProjectRpcAsync getProjectService(); /** * @return the ProjectID for the project the View is displaying. */ long getProjectId(); /** * Notifies the Presenter that a new Component has been created. */ public void createComponent(Component component); /** * Updates the given component in the database. */ public void updateComponent(Component componentToUpdate); public void updateSignoff(Component attribute, boolean newSignoff); /** * Removes the given component from the Project. */ public void removeComponent(Component componentToRemove); /** * Reorders the project's list of Components. */ public void reorderComponents(List<Long> newOrder); } /** * Bind the view and the underlying presenter it communicates with. */ public void setPresenter(Presenter presenter); /** * Initialize user interface elements with the given set of Components. */ public void setProjectComponents(List<Component> components); public void refreshComponent(Component component); public void setProjectLabels(Collection<String> projectLabels); public void setSignoffs(List<Signoff> signoffs); /** * Updates the view to enable editing of component data. */ public void enableEditing(); /** * Converts the view into a GWT widget. */ public Widget asWidget(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/view/ComponentsView.java
Java
asf20
2,742
// 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.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.LayoutPanel; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootLayoutPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpc; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; /** * Entry point for Test Analytics application. * * @author jimr@google.com (Jim Reardon) */ public class TaEntryPoint implements EntryPoint { private Panel contentPanel; private ProjectRpcAsync projectService; private UserRpcAsync userService; private DataRpcAsync dataService; private static final String HOMEPAGE_HISTORY_TOKEN = "/homepage"; // URL related error messages. private static final String INVALID_URL = "Invalid URL"; private static final String INVALID_URL_TEXT = "The page could not be found."; private static final String INVALID_PROJECT_ID_TEXT = "No project with that ID was found."; // Project-load related error messages. private static final String ERROR_LOADING_PROJECT = "Error loading project"; private static final String ERROR_LOADING_PROJECT_TEXT = "There was an error loading the requested project"; private static final String PROJECT_NOT_FOUND = "Project not found"; private static final String PROJECT_ID_NOT_FOUND_TEXT = "No project with that ID was found."; /** UI for the currently opened project. */ private TaApplication currentApplicationInstance = null; /** * Entry point for the application. */ @Override public void onModuleLoad() { projectService = GWT.create(ProjectRpc.class); userService = GWT.create(UserRpc.class); dataService = GWT.create(DataRpc.class); contentPanel = new LayoutPanel(); RootLayoutPanel.get().add(contentPanel); // Handle history changes. (Such as clicking a navigation hyperlink.) History.addValueChangeHandler(new ValueChangeHandler<String>() { @Override public void onValueChange(ValueChangeEvent<String> event) { String historyToken = event.getValue(); handleUrl(historyToken); } }); handleUrl(History.getToken()); } /** * Handles the URL, updating any UI elements for the current Testify application if necessary. */ private void handleUrl(String url) { // Intercept well-known pages. if ((url.length() == 0) || ("/".equals(url)) || (HOMEPAGE_HISTORY_TOKEN.equals(url))) { displayHomePage(); return; } // Expected format: "/project-id/target-page" // or: "/project-id/target-page/page-data" (project data is passed into the project page). // Thus part 0 will be an empty string, part 1 will be the project ID, part 2 the page name, // and part 3 the page data. String[] parts = url.split("/"); if ((parts.length < 2) || (parts[0].length() != 0)) { displayErrorPage(INVALID_URL, INVALID_URL_TEXT); return; } // The first part, the project ID. Long projectId = tryParseLong(parts[1]); if (projectId == null) { displayErrorPage(INVALID_URL, INVALID_PROJECT_ID_TEXT); return; } // Page name. String pageName = (parts.length > 2 ? parts[2] : null); // Page has data that should be sent to the target page. String pageData = (parts.length > 3 ? parts[3] : null); // Attempt to switch the page view. if (currentApplicationInstance != null && (currentApplicationInstance.getProject().getProjectId().equals(projectId))) { currentApplicationInstance.switchToPage(pageName, pageData); } else { // Otherwise, attempt to load the project and switch the view. loadProjectAndSwitchToUrl(projectId, url); } } /** * Performs an asynchronous load of a project with the given ID name. Afterwards, navigates to the * target URL. */ private void loadProjectAndSwitchToUrl(final long projectId, final String targetUrl) { projectService.getProjectById(projectId, new AsyncCallback<Project>() { @Override public void onFailure(Throwable caught) { displayErrorPage(ERROR_LOADING_PROJECT, ERROR_LOADING_PROJECT_TEXT); } @Override public void onSuccess(Project result) { if (result == null) { displayErrorPage(PROJECT_NOT_FOUND, PROJECT_ID_NOT_FOUND_TEXT); } else { displayProjectView(result); handleUrl(targetUrl); } } }); } /** * Switches the application's view to displays an error message. */ private void displayErrorPage(String errorType, String errorMessage) { GWT.log("General error: " + errorType); GeneralErrorPage errorPage = new GeneralErrorPage(); errorPage.setErrorType(errorType); errorPage.setErrorText(errorMessage); setPageContent(errorPage); } /** * Switches the application's view to the home page. */ private void displayHomePage() { final HomePage homePage = new HomePage(projectService, userService); setPageContent(homePage); } /** * Switches the application's view to a specific Project. */ public void displayProjectView(Project project) { // All projects must be serialized (have a Project ID) first. if (project.getProjectId() == null) { return; } GWT.log("Switching to view project " + project.getProjectId().toString()); currentApplicationInstance = new TaApplication(project, projectService, userService, dataService); setPageContent(currentApplicationInstance); } /** * Sets the GWT page to display the provided content. */ private void setPageContent(Widget content) { contentPanel.clear(); contentPanel.add(content); } /** * Attempts to parse the given string as integer, if not returns null. */ private Long tryParseLong(String text) { Long result = null; try { return Long.parseLong(text); } catch (NumberFormatException nfe) { return null; } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/TaEntryPoint.java
Java
asf20
7,319
// 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.client; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.dom.client.KeyCodes; import com.google.gwt.event.dom.client.KeyDownEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DeckPanel; import com.google.gwt.user.client.ui.Grid; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.view.widgets.ProjectFavoriteStar; import com.google.testing.testify.risk.frontend.client.view.widgets.PageHeaderWidget; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.TestProjectCreatorRpc; import com.google.testing.testify.risk.frontend.shared.rpc.TestProjectCreatorRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; import java.util.List; /** * Home page widget for Test Analytics. * * @author jimr@google.com (Jim Reardon) */ public class HomePage extends Composite { /** * Used to wire parent class to associated UI Binder. */ interface HomePageUiBinder extends UiBinder<Widget, HomePage> {} private static final HomePageUiBinder uiBinder = GWT.create(HomePageUiBinder.class); @UiField protected ListBox userProjectsListBox; @UiField protected CheckBox justMyProjectsCheckbox; @UiField protected Grid projectsGrid; @UiField protected Button createProjectButton; @UiField protected Button createTestProjectButton; @UiField protected Button createDataSourcesButton; @UiField protected DeckPanel newProjectPanel; @UiField protected TextBox newProjectName; @UiField protected Button newProjectOkButton; @UiField protected Button newProjectCancelButton; @UiField public VerticalPanel adminPanel; private List<Project> allProjects; private List<Long> starredProjects; private final ProjectRpcAsync projectService; private final UserRpcAsync userService; private TestProjectCreatorRpcAsync creatorService = null; private static final int GRID_COLUMNS = 3; // The widgets that are a part of the DeckPanel are created through the UI binder, in this order. private static final int DECK_WIDGET_NEW_BUTTON = 0; private static final int DECK_WIDGET_NAME_PANEL = 1; /** * Constructs a HomePage object. */ public HomePage(ProjectRpcAsync projectService, UserRpcAsync userService) { this.projectService = projectService; this.userService = userService; initWidget(uiBinder.createAndBindUi(this)); newProjectPanel.setAnimationEnabled(true); // The widgets that are a part of the DeckPanel are created through the UI binder. newProjectPanel.showWidget(DECK_WIDGET_NEW_BUTTON); justMyProjectsCheckbox.setValue(false); loadProjectList(); setAdminPanelVisibleIfAdmin(); } @UiFactory public PageHeaderWidget createPageHeaderWidget() { return new PageHeaderWidget(userService); } @UiHandler("createDataSourcesButton") public void onCreateDataSourcesClicked(ClickEvent event) { if (creatorService == null) { creatorService = GWT.create(TestProjectCreatorRpc.class); } creatorService.createStandardDataSources(TaCallback.getNoopCallback()); } @UiHandler("justMyProjectsCheckbox") void onJustMyProjectsCheckboxClicked(ClickEvent event) { updateProjectsList(); } @UiHandler("newProjectName") protected void onNewProjectEnter(KeyDownEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { doCreateProject(newProjectName.getText()); } } @UiHandler("newProjectOkButton") protected void onNewProjectOkClicked(ClickEvent event) { doCreateProject(newProjectName.getText()); } @UiHandler("newProjectCancelButton") protected void onNewProjectCancelClicked(ClickEvent event) { newProjectName.setText(""); newProjectPanel.showWidget(DECK_WIDGET_NEW_BUTTON); } @UiHandler("createProjectButton") void onCreateProjectButtonClicked(ClickEvent event) { newProjectPanel.showWidget(DECK_WIDGET_NAME_PANEL); newProjectName.setFocus(true); } @UiHandler("userProjectsListBox") void onSelectNewProject(ChangeEvent event) { int selectedIndex = userProjectsListBox.getSelectedIndex(); gotoProject(userProjectsListBox.getValue(selectedIndex)); } private void loadProjectList() { userService.getStarredProjects( new TaCallback<List<Long>>("querying starred projects") { @Override public void onSuccess(List<Long> result) { starredProjects = result; updateProjectsList(); } }); displayMessageInGrid("Loading project list..."); projectService.query("", new TaCallback<List<Project>>("querying projects") { @Override public void onSuccess(List<Project> result) { allProjects = result; updateProjectsList(); } }); } private void setAdminPanelVisibleIfAdmin() { userService.hasAdministratorAccess(new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { adminPanel.setVisible(true); } } @Override public void onFailure(Throwable caught) { return; } }); userService.isDevMode(new AsyncCallback<Boolean>() { @Override public void onSuccess(Boolean result) { if (result) { adminPanel.setVisible(true); } } @Override public void onFailure(Throwable caught) { return; } }); } private void doCreateProject(String projectName) { projectName = projectName.trim(); if (projectName.length() < 1) { Window.alert("Enter a valid project name."); return; } final Project newProject = new Project(); newProject.setName(projectName); projectService.createProject(newProject, new TaCallback<Long>("creating new project") { @Override public void onSuccess(Long result) { newProject.setProjectId(result); gotoProject(result.toString()); } }); } @UiHandler("createTestProjectButton") void onCreateTestProjectButtonClicked(ClickEvent event) { if (creatorService == null) { creatorService = GWT.create(TestProjectCreatorRpc.class); } creatorService.createTestProject( new TaCallback<Project>("creating new project") { @Override public void onSuccess(Project result) { gotoProject(result.getProjectId().toString()); } }); } /** * Displays a single message in place of the projects grid. */ private void displayMessageInGrid(String message) { projectsGrid.clear(); projectsGrid.resize(1, 1); projectsGrid.setWidget(0, 0, new Label(message)); } /** * Fills the list of projects on the HomePage widget with the given projects. Also replaces the * label describing the projects with the provided text. */ private void updateProjectsList() { if (allProjects != null && starredProjects != null) { List<Project> userProjects = Lists.newArrayList(); List<Project> publicProjects = Lists.newArrayList(); for (Project p : allProjects) { if (p.getCachedAccessLevel().hasAccess(ProjectAccess.EXPLICIT_VIEW_ACCESS)) { userProjects.add(p); } else if (starredProjects.contains(p.getProjectId())) { userProjects.add(p); } else { publicProjects.add(p); } } // Update drop-down. userProjectsListBox.clear(); userProjectsListBox.addItem("", ""); for (Project p : userProjects) { userProjectsListBox.addItem(p.getName(), p.getProjectId().toString()); } userProjectsListBox.setSelectedIndex(0); // Update the grid. if (justMyProjectsCheckbox.getValue().equals(false)) { userProjects.addAll(publicProjects); } // Special case for zero projects. if (userProjects.size() < 1) { displayMessageInGrid("No projects to display."); return; } projectsGrid.clear(); int rows = ((userProjects.size() - 1) / GRID_COLUMNS) + 1; projectsGrid.resize(rows, GRID_COLUMNS); for (int projectIndex = 0; projectIndex < userProjects.size(); projectIndex++) { final Project project = userProjects.get(projectIndex); ProjectFavoriteStar favoriteStar = new ProjectFavoriteStar(); favoriteStar.attachToProject(project.getProjectId()); if (starredProjects.contains(project.getProjectId())) { favoriteStar.setStarredStatus(true); } Anchor nameWidget = new Anchor(project.getName()); nameWidget.addStyleName("tty-HomePageProjectsGridProjectName"); HorizontalPanel projectWidget = new HorizontalPanel(); projectWidget.add(favoriteStar); projectWidget.add(nameWidget); projectWidget.addStyleName("tty-HomePageProjectsGridProject"); nameWidget.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { gotoProject(project.getProjectId().toString()); } }); int targetColumn = projectIndex % GRID_COLUMNS; int targetRow = projectIndex / GRID_COLUMNS; projectsGrid.setWidget(targetRow, targetColumn, projectWidget); } } } private void gotoProject(String projectId) { History.newItem("/" + projectId + "/project-details"); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/HomePage.java
Java
asf20
11,224
// 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.client; import com.google.gwt.core.client.GWT; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; /** * General error page for unrecoverable errors. * * @author chrsmith@google.com (Chris Smith) */ public class GeneralErrorPage extends Composite { /** Used to wire parent class to associated UI Binder. */ interface GeneralErrorPageUiBinder extends UiBinder<Widget, GeneralErrorPage> {} private static final GeneralErrorPageUiBinder uiBinder = GWT.create(GeneralErrorPageUiBinder.class); @UiField public Label errorType; @UiField public Label errorText; public GeneralErrorPage() { initWidget(uiBinder.createAndBindUi(this)); } public void setErrorType(String errorTypeText) { errorType.setText(errorTypeText); } public void setErrorText(String text) { this.errorText.setText(text); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/GeneralErrorPage.java
Java
asf20
1,683
// 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.client.riskprovider; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.model.CapabilityIntersectionData; import java.util.List; /** * Interface for new ways to provide a 'Risk' view for the application. * * @author chrsmith@google.com (Chris Smith) */ public interface RiskProvider { /** * @return a one or two word description of the risk provider. E.g. "Defects" or "Test coverage". */ public String getName(); /** * Inform the risk provider of all available capabilities. This gives it a chance to establish * any baselines and/or query any external data sources. */ public void initialize(List<CapabilityIntersectionData> projectData); /** * Calculates the risk for a given list of capabilities (all sharing the same parent Attribute * and Component.) * * @return risk value between -1.0 and 1.0. A value of 0.0 indicates negligible risk, -1.0 lots * of risk mitigation, and 1.0 indicates very high risk. */ public double calculateRisk(CapabilityIntersectionData targetCell); /** * Surface any custom UI when a risk cell is clicked. Will be displayed on a dialog box with an * OK button. */ public Widget onClick(CapabilityIntersectionData targetCell); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/RiskProvider.java
Java
asf20
1,930
// 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.client.riskprovider.impl; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; 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.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import java.util.HashSet; import java.util.List; /** * {@link RiskProvider} showing Risk due to outstanding code defects. * * For example, if outstanding bugs are spread across all existing Attribute x Component pairs, then * there is relatively low risk due to bugs. However, if one Attribute x Component pair has a large * concentration of bugs then it should be investigated. * * The higher the risk returned, the more risky that area is. * * @author chrsmith@google.com (Chris Smith) */ public class BugRiskProvider implements RiskProvider { private final HashSet<Bug> unassignedBugs = new HashSet<Bug>(); private final Multimap<Long, Bug> lookupByAttribute = HashMultimap.create(); private final Multimap<Long, Bug> lookupByComponent = HashMultimap.create(); private final Multimap<Long, Bug> lookupByCapability = HashMultimap.create(); // Bugs not associated with an Attribute or Component. (General risk.) private static final double RISK_FROM_UNASSIGNED = 0.00; // Bugs associated with the Attribute. private static final double RISK_FROM_ATTRIBUTE = 0.25; // Bugs associated with the Component. private static final double RISK_FROM_COMPONENT = 0.25; // Bugs associated with the Capability. private static final double RISK_FROM_CAPABILITY = 1.0; @Override public String getName() { return "Bugs"; } /** * Asynchronously loads project bug information. */ @Override public void initialize(List<CapabilityIntersectionData> projectData) { DataRpcAsync bugService = GWT.create(DataRpc.class); long projectId = projectData.get(0).getParentComponent().getParentProjectId(); bugService.getProjectBugsById(projectId, new TaCallback<List<Bug>>("Querying Bugs") { @Override public void onSuccess(List<Bug> result) { lookupByAttribute.clear(); lookupByComponent.clear(); lookupByCapability.clear(); unassignedBugs.clear(); for (Bug bug : result) { lookupByAttribute.put(bug.getTargetAttributeId(), bug); lookupByComponent.put(bug.getTargetComponentId(), bug); lookupByCapability.put(bug.getTargetCapabilityId(), bug); if (bug.getTargetAttributeId() == null && bug.getTargetComponentId() == null && bug.getTargetCapabilityId() == null) { unassignedBugs.add(bug); } } } }); } /** * Returns the risk caused by outstanding bugs (based solely on bug count). */ @Override public double calculateRisk(CapabilityIntersectionData targetCell) { long attributeId = targetCell.getParentAttribute().getAttributeId(); long componentId = targetCell.getParentComponent().getComponentId(); // Bugs attached to Attributes or Components add risk to the whole Attribute and the whole // Component. It is OK if we double-count risk. double riskFromBugs = 0.0; riskFromBugs += RISK_FROM_UNASSIGNED * unassignedBugs.size(); riskFromBugs += RISK_FROM_ATTRIBUTE * lookupByAttribute.get(attributeId).size(); riskFromBugs += RISK_FROM_COMPONENT * lookupByComponent.get(componentId).size(); for (Capability capability : targetCell.getCapabilities()) { riskFromBugs += RISK_FROM_CAPABILITY * lookupByCapability.get(capability.getCapabilityId()).size(); } return riskFromBugs; } /** * Returns a {@code Widget} to show when an Attribute x Component pair is clicked. */ @Override public Widget onClick(CapabilityIntersectionData targetCell) { VerticalPanel content = new VerticalPanel(); long attributeId = targetCell.getParentAttribute().getAttributeId(); long componentId = targetCell.getParentComponent().getComponentId(); for (Bug bug : lookupByComponent.get(componentId)) { String linkText = "Component - " + Long.toString(bug.getExternalId()) + ": " + bug.getTitle(); Anchor anchor = new Anchor(linkText, bug.getBugUrl()); content.add(anchor); } for (Bug bug : lookupByAttribute.get(attributeId)) { String linkText = "Attribute - " + Long.toString(bug.getExternalId()) + ": " + bug.getTitle(); Anchor anchor = new Anchor(linkText, bug.getBugUrl()); content.add(anchor); } for (Capability capability : targetCell.getCapabilities()) { long capabilityId = capability.getCapabilityId(); for (Bug bug : lookupByCapability.get(capabilityId)) { String linkText = "Capability - " + Long.toString(bug.getExternalId()) + ": " + bug.getTitle(); Anchor anchor = new Anchor(linkText, bug.getBugUrl()); content.add(anchor); } } String labelText = "Unassigned - " + unassignedBugs.size(); Label label = new Label(labelText); content.add(label); if (content.getWidgetCount() == 0) { content.add(new Label("No bugs associated with this cell.")); } return content; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/impl/BugRiskProvider.java
Java
asf20
6,489
// 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.client.riskprovider.impl; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; import com.google.testing.testify.risk.frontend.model.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Risk provider showing risk due to code churn. It works by analyzing individual changes which * each contain a list of 'directories they care about' and then scanning all checkins to see * if they touched any directories of interest. * * Note that if a checkin is in "foo\bar\baz", Components which care about "foo" and "foo\bar" will * both have the risk associated with the checkin. To facilitate risk cascading down a directory * hierarchy, a tree will be created where each node is a directory name. * * @author chrsmith@google.com (Chris Smith) */ public class CodeChurnRiskProvider implements RiskProvider { // TODO(chrsmith): While time-efficient, creating a checkin lookup tree is not the simplest // solution. Perhaps we can use a Multimap<String, Checkin> instead. Note however that we // would need to walk every Key and see if the Key starts with the target directory in the case // that the Component cares about "alpha\beta" and a checkin touches "alpha\beta\gamma". /** Tree used to quickly lookup checkins based on a code directory. */ CheckinDirectoryTreeNode treeRoot = new CheckinDirectoryTreeNode(); @Override public double calculateRisk(CapabilityIntersectionData targetCell) { Set<Checkin> relevantCheckins = getCheckinsRealtedToRiskCell(targetCell); return relevantCheckins.size() * 0.20; } @Override public String getName() { return "Code churn"; } @Override public void initialize(List<CapabilityIntersectionData> projectData) { DataRpcAsync dataService = GWT.create(DataRpc.class); long projectId = projectData.get(0).getParentComponent().getParentProjectId(); dataService.getProjectCheckinsById(projectId, new TaCallback<List<Checkin>>("Querying Checkins") { @Override public void onSuccess(List<Checkin> result) { initializeCheckinLookup(result); } }); } @Override public Widget onClick(CapabilityIntersectionData targetCell) { VerticalPanel checkinsPanel = new VerticalPanel(); Set<Checkin> relevantCheckins = getCheckinsRealtedToRiskCell(targetCell); if (relevantCheckins.size() == 0) { checkinsPanel.add(new Label("No checkins are associated with this cell.")); } else { for (Checkin checkin : relevantCheckins) { String linkText = Long.toString(checkin.getExternalId()) + ": " + checkin.getSummary(); // Display only 100 characters of a checkin summary. if (linkText.length() > 100) { linkText = linkText.substring(0, 97) + "..."; } checkinsPanel.add(new Anchor(linkText, checkin.getChangeUrl())); } } return checkinsPanel; } /** * Initialize the checkin directory tree data structure based on the directories touched by all * known checkins. */ private void initializeCheckinLookup(List<Checkin> checkins) { treeRoot = new CheckinDirectoryTreeNode(); for (Checkin checkin : checkins) { for (String directoryTouched : checkin.getDirectoriesTouched()) { // NOTE: This means that if a checkin touches directory A and directory B, then // the checkin will be double-counted if the component looks for checkins in both A and B. treeRoot.addCheckin(directoryTouched, checkin); } } } /** * @return the checkins relevant to the risk provider cell. (Based on the current checkin * directory tree in memory.) */ private Set<Checkin> getCheckinsRealtedToRiskCell(CapabilityIntersectionData cell) { // TODO(chrsmith): Implement this by relying on ComponentSuperLabels. return new HashSet<Checkin>(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/impl/CodeChurnRiskProvider.java
Java
asf20
5,068
// 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.client.riskprovider.impl; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.testing.testify.risk.frontend.model.Checkin; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; /** * Node in a tree representing a directory hierarchy as it applies to code checkins. * * @author chrsmith@google.com (Chris Smith) */ public class CheckinDirectoryTreeNode { /** The name of this directory, e.g. "alpha" */ private final String directoryName; /** Child directories. */ private final HashMap<String, CheckinDirectoryTreeNode> childDirectories = new HashMap<String, CheckinDirectoryTreeNode>(); /** * All checkins which have touched this directory or one of its children. * * NOTE: As you descend down the tree this will be strictly additive. For deep trees with many * checkins it might be more efficent to store a parent node and walk up the tree rebuilding the * set of checkins on each node. */ private final Set<Checkin> checkins = new HashSet<Checkin>(); /** * Creates a new root directory tree node. */ public CheckinDirectoryTreeNode() { directoryName = ""; } /** * Creates a new directory tree node with the given parent and directory name. */ public CheckinDirectoryTreeNode(CheckinDirectoryTreeNode parent, String directoryName) { this.directoryName = directoryName; } public String getDirectoryName() { return directoryName; } public ImmutableMap<String, CheckinDirectoryTreeNode> getChildNodes() { ImmutableMap<String, CheckinDirectoryTreeNode> immutableMap = ImmutableMap.copyOf(childDirectories); return immutableMap; } public ImmutableSet<Checkin> getCheckins() { ImmutableSet<Checkin> immutableSet = ImmutableSet.copyOf(checkins); return immutableSet; } /** * Returns the list of all checkins that happen in the directory under this node. For example, * if the checkinDirectory was "alpha/beta" then it would return all bugs under: * this.getChildNodes().get("alpha").getChildNodes().get("beta").getCheckins() */ public ImmutableSet<Checkin> getCheckinsUnder(String checkinDirectory) { if (checkinDirectory.trim().isEmpty()) { return getCheckins(); } LinkedList<String> directoryNames = getDirectoryAsLinkedList(checkinDirectory); CheckinDirectoryTreeNode node = this; while (!directoryNames.isEmpty()) { String directoryName = directoryNames.remove(); if (node.childDirectories.containsKey(directoryName)) { node = node.childDirectories.get(directoryName); } else { return ImmutableSet.of(); } } return node.getCheckins(); } /** * @return the input string represented as a linked list, split by '/' or '\' characters. */ private LinkedList<String> getDirectoryAsLinkedList(String checkinDirectory) { // Normalize folder path separators. if (checkinDirectory.indexOf('|') != -1) { throw new IllegalArgumentException("The checkin directory contains an invalid character '|'"); } checkinDirectory = checkinDirectory.replace('/', '|'); checkinDirectory = checkinDirectory.replace('\\', '|'); // Convert an array of directory names into a linked list for more efficent processing. String[] directories = checkinDirectory.split("|"); LinkedList<String> list = Lists.newLinkedList(); for (String s : directories) { list.add(s); } return list; } /** * Adds the given checkin to the directory tree, building child nodes as necessary. */ public void addCheckin(String checkinDirectory, Checkin checkin) { LinkedList<String> directoryNames = getDirectoryAsLinkedList(checkinDirectory); addCheckin(directoryNames, checkin); } /** * Adds a checkin to the tree node under the given path of directory names. * * @param pathToCheckin List of directories left in the path. E.g. directory "foo\bar\ram" will * become "foo" -> "bar -> "ram" * @param checkin the checkin associated with the tree. Note that it will be attached to each * node up to the root. (Since the checkin is 'under' the root.) */ private void addCheckin(LinkedList<String> pathToCheckin, Checkin checkin) { checkins.add(checkin); if (!pathToCheckin.isEmpty()) { // Get the head element and chop it from the list. String nextDirectory = pathToCheckin.remove(); if (!childDirectories.containsKey(nextDirectory)) { CheckinDirectoryTreeNode newChild = new CheckinDirectoryTreeNode(this, nextDirectory); childDirectories.put(nextDirectory, newChild); } CheckinDirectoryTreeNode child = childDirectories.get(nextDirectory); child.addCheckin(pathToCheckin, checkin); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/impl/CheckinDirectoryTreeNode.java
Java
asf20
5,543
// 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.client.riskprovider.impl; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; import com.google.testing.testify.risk.frontend.client.view.widgets.RiskCapabilityWidget; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.shared.util.RiskUtil; import java.util.List; /** * Provides a Risk calculation based on static project data. (Risk associated with individual * Capabilities.) * * @author chrsmith@google.com (Chris Smith) */ public class StaticRiskProvider implements RiskProvider { @Override public String getName() { return "Inherent risk"; } @Override public void initialize(List<CapabilityIntersectionData> projectData) { } @Override public double calculateRisk(CapabilityIntersectionData targetCell) { double localRisk = 0.0f; // Calculate the 'risk' associated with these Capabilities. for (Capability capability : targetCell.getCapabilities()) { localRisk += RiskUtil.determineRisk(capability); } return localRisk; } @Override public Widget onClick(CapabilityIntersectionData targetCell) { VerticalPanel panel = new VerticalPanel(); panel.setStyleName("tty-CapabilitiesContainer"); String aName = targetCell.getParentAttribute().getName(); String cName = targetCell.getParentComponent().getName(); Label name = new Label(cName + " is " + aName); name.setStyleName("tty-CapabilitiesContainerTitle"); panel.add(name); for (Capability capability : targetCell.getCapabilities()) { RiskCapabilityWidget widget = new RiskCapabilityWidget(capability, RiskUtil.getRiskText((capability))); widget.setRiskContent(new Label(RiskUtil.getRiskExplanation(capability))); panel.add(widget); } return panel; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/impl/StaticRiskProvider.java
Java
asf20
2,720
// 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.client.riskprovider.impl; import com.google.common.base.Predicate; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.ui.Anchor; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.TaCallback; import com.google.testing.testify.risk.frontend.client.riskprovider.RiskProvider; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.CapabilityIntersectionData; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync; import java.util.HashSet; import java.util.List; /** * Provides the mitigation contributed by existing test coverage. (Testcases alone, not code * coverage or recent test results.) * * @author chrsmith@google.com (Chris Smith) */ public class TestCoverageRiskProvider implements RiskProvider { private final Multimap<Long, TestCase> testcaseByAttributeLookup = HashMultimap.create(); private final Multimap<Long, TestCase> testcaseByComponentLookup = HashMultimap.create(); private final Multimap<Long, TestCase> testcaseByCapabilityLookup = HashMultimap.create(); @Override public String getName() { return "Test coverage"; } @Override public void initialize(List<CapabilityIntersectionData> projectData) { DataRpcAsync dataService = GWT.create(DataRpc.class); long projectId = projectData.get(0).getParentComponent().getParentProjectId(); dataService.getProjectTestCasesById(projectId, new TaCallback<List<TestCase>>("Querying TestCases") { @Override public void onSuccess(List<TestCase> result) { initializeTestCaseLookups(result); } }); } /** * Initializes class fields related to looking up testcases by Attribute, Component, or * Capability IDs. */ private void initializeTestCaseLookups(List<TestCase> testCases) { for (TestCase test : testCases) { for (String testcaseTag : test.getTags()) { // Search test case tags for IDs prefixed with descriptors such as "Component:13452" String[] parts = testcaseTag.split(":"); if (parts.length != 2) { continue; } try { if (parts[0].equals("Attribute")) { testcaseByAttributeLookup.put(Long.parseLong(parts[1]), test); } else if (parts[0].equals("Capability")) { testcaseByCapabilityLookup.put(Long.parseLong(parts[1]), test); } else if (parts[0].equals("Component")) { testcaseByComponentLookup.put(Long.parseLong(parts[1]), test); } } catch (NumberFormatException nfe) { // Notify the user of a malformed testcase tag. StringBuilder errorMessage = new StringBuilder(); errorMessage.append("Error processing a testcase with a malformed tag. "); errorMessage.append("Testcase tag: '"); errorMessage.append(testcaseTag); errorMessage.append("' found on testcase '"); errorMessage.append(test.getTitle()); errorMessage.append("'"); NotificationUtil.displayErrorMessage(errorMessage.toString()); } } } } /** * Returns the list of test cases associated with a given risk cell. */ public List<TestCase> getCellTestCases(CapabilityIntersectionData targetCell) { List<TestCase> testCases = Lists.newArrayList(); long attributeId = targetCell.getParentAttribute().getAttributeId(); if (testcaseByAttributeLookup.containsKey(attributeId)) { testCases.addAll(testcaseByAttributeLookup.get(attributeId)); } long componentId = targetCell.getParentComponent().getComponentId(); if (testcaseByComponentLookup.containsKey(componentId)) { testCases.addAll(testcaseByComponentLookup.get(componentId)); } if (targetCell.getCapabilities() != null) { for (Capability capability : targetCell.getCapabilities()) { long capabilityId = capability.getCapabilityId(); if (testcaseByCapabilityLookup.containsKey(capabilityId)) { testCases.addAll(testcaseByCapabilityLookup.get(capabilityId)); } } } // Remove any duplicate entries. final HashSet<Long> testCaseIds = new HashSet<Long>(); return Lists.newArrayList(Iterables.filter(testCases, new Predicate<TestCase>() { @Override public boolean apply(TestCase input) { if (testCaseIds.contains(input.getExternalId())) { return false; } else { testCaseIds.add(input.getExternalId()); return true; } } })); } @Override public double calculateRisk(CapabilityIntersectionData targetCell) { List<TestCase> testCases = getCellTestCases(targetCell); // Test coverage mitigates risk, so the value returned is negative. return testCases.size() * -0.15; } @Override public Widget onClick(CapabilityIntersectionData targetCell) { List<TestCase> testCases = getCellTestCases(targetCell); VerticalPanel panel = new VerticalPanel(); if (testCases.size() == 0) { panel.add(new Label("No test cases are associated with this cell.")); } else { for (TestCase testCase : testCases) { panel.add(new Anchor(testCase.getTitle(), testCase.getTestCaseUrl())); } } return panel; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/riskprovider/impl/TestCoverageRiskProvider.java
Java
asf20
6,533
// 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.client.event; import com.google.gwt.event.shared.EventHandler; /** * Event handler for {@link WidgetsReorderedEvent}. * * @author chrsmith@google.com (Chris Smith) */ public interface WidgetsReorderedHandler extends EventHandler { public void onWidgetsReordered(WidgetsReorderedEvent event); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/WidgetsReorderedHandler.java
Java
asf20
961
// 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.client.event; import com.google.gwt.event.shared.GwtEvent; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Project; /** * Event type fired when the current project does not contain any elements of a specific * type. Note that this element is reused whenever the project is out of _any_ element type, so * consumers will have to filter appropriately by calling the projectHasNoXXX() method. * appropriately. * * @author chrsmith@google.com (Chris Smith) */ public class ProjectHasNoElementsEvent extends GwtEvent<ProjectHasNoElementsHandler> { private static final Type<ProjectHasNoElementsHandler> TYPE = new Type<ProjectHasNoElementsHandler>(); // Default to false, implying the project HAS elements of the given types. private final AccElementType accElementType; private final Project project; public ProjectHasNoElementsEvent(Project project, AccElementType accElementType) { this.project = project; this.accElementType = accElementType; } public Project getProject() { return project; } public boolean projectHasNoAttributes() { return accElementType.equals(AccElementType.ATTRIBUTE); } public boolean projectHasNoComponents() { return accElementType.equals(AccElementType.COMPONENT); } public boolean projectHasNoCapabilities() { return accElementType.equals(AccElementType.CAPABILITY); } public static Type<ProjectHasNoElementsHandler> getType() { return TYPE; } @Override protected void dispatch(ProjectHasNoElementsHandler handler) { handler.onProjectHasNoElements(this); } @Override public Type<ProjectHasNoElementsHandler> getAssociatedType() { return TYPE; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectHasNoElementsEvent.java
Java
asf20
2,412
// 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.client.event; import com.google.gwt.event.shared.EventHandler; /** * Event handler for {@link DialogClosedEvent}. * * @author chrsmith@google.com (Chris Smith) */ public interface DialogClosedHandler extends EventHandler { public void onDialogClosed(DialogClosedEvent event); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/DialogClosedHandler.java
Java
asf20
945
// 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.client.event; import com.google.common.collect.ImmutableList; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.user.client.ui.Widget; import java.util.List; /** * Event type fired when a list of widgets has been reordered. * * @author chrsmith@google.com (Chris Smith) */ public class WidgetsReorderedEvent extends GwtEvent<WidgetsReorderedHandler> { private static final Type<WidgetsReorderedHandler> TYPE = new Type<WidgetsReorderedHandler>(); private final ImmutableList<Widget> widgets; public WidgetsReorderedEvent(List<Widget> widgets) { this.widgets = ImmutableList.copyOf(widgets); } public ImmutableList<Widget> getWidgetOrdering() { return widgets; } public static Type<WidgetsReorderedHandler> getType() { return TYPE; } @Override protected void dispatch(WidgetsReorderedHandler handler) { handler.onWidgetsReordered(this); } @Override public Type<WidgetsReorderedHandler> getAssociatedType() { return TYPE; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/WidgetsReorderedEvent.java
Java
asf20
1,661
// 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.client.event; import com.google.gwt.event.shared.GwtEvent; import com.google.testing.testify.risk.frontend.model.Project; /** * Event fired when a project has a change in value. * * @author jimr@google.com (Jim Reardon) */ public class ProjectChangedEvent extends GwtEvent<ProjectChangedHandler> { private static final Type<ProjectChangedHandler> TYPE = new Type<ProjectChangedHandler>(); private final Project project; public ProjectChangedEvent(Project project) { this.project = project; } public Project getProject() { return project; } @Override protected void dispatch(ProjectChangedHandler handler) { handler.onProjectChanged(this); } public static Type<ProjectChangedHandler> getType() { return TYPE; } @Override public Type<ProjectChangedHandler> getAssociatedType() { return TYPE; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectChangedEvent.java
Java
asf20
1,513
// 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.client.event; import com.google.gwt.event.shared.EventHandler; /** * Event handler for {@link ProjectElementAddedEvent}. * * @author chrsmith@google.com (Chris Smith) */ public interface ProjectElementAddedHandler extends EventHandler { public void onProjectElementAdded(ProjectElementAddedEvent event); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectElementAddedHandler.java
Java
asf20
973
// 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.client.event; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; /** * Provides registration for {@link DialogClosedHandler} instances. * * @author chrsmith@google.com (Chris Smith) */ public interface HasDialogClosedHandler extends HasHandlers { HandlerRegistration addDialogClosedHandler(DialogClosedHandler handler); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/HasDialogClosedHandler.java
Java
asf20
1,042
// 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.client.event; import com.google.gwt.event.shared.EventHandler; /** * Handler to listen for changes to project details. * * @author jimr@google.com (Jim Reardon) */ public interface ProjectChangedHandler extends EventHandler { public void onProjectChanged(ProjectChangedEvent event); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectChangedHandler.java
Java
asf20
952
// 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.client.event; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.event.shared.HasHandlers; /** * Provides registration for {@link WidgetsReorderedHandler} instances. * * @author chrsmith@google.com (Chris Smith) */ public interface HasWidgetsReorderedHandler extends HasHandlers { HandlerRegistration addWidgetsReorderedHandler(WidgetsReorderedHandler handler); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/HasWidgetsReorderedHandler.java
Java
asf20
1,058
// 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.client.event; import com.google.gwt.event.shared.GwtEvent; /** * Event type fired when Dialog Boxes are closed. * * @author chrsmith@google.com (Chris Smith) */ public class DialogClosedEvent extends GwtEvent<DialogClosedHandler> { public enum DialogResult { OK, Cancel } private static final Type<DialogClosedHandler> TYPE = new Type<DialogClosedHandler>(); private final DialogResult result; public DialogClosedEvent(DialogResult result) { this.result = result; } public DialogResult getResult() { return result; } public static Type<DialogClosedHandler> getType() { return TYPE; } @Override protected void dispatch(DialogClosedHandler handler) { handler.onDialogClosed(this); } @Override public Type<DialogClosedHandler> getAssociatedType() { return TYPE; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/DialogClosedEvent.java
Java
asf20
1,495
// 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.client.event; import com.google.gwt.event.shared.GwtEvent; 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; /** * Event type fired when the current project adds a new project element. (Attribute, * Component, or Capability.). Note that this event is used whenever _any_ project elements of any * type are created. Consumers will need to call the isXXXAddedEvent() methods and filter * appropriately. * * @author chrsmith@google.com (Chris Smith) */ public class ProjectElementAddedEvent extends GwtEvent<ProjectElementAddedHandler> { private static final Type<ProjectElementAddedHandler> TYPE = new Type<ProjectElementAddedHandler>(); private final Attribute attribute; private final Component component; private final Capability capability; public ProjectElementAddedEvent(Attribute attribute) { this.attribute = attribute; this.component = null; this.capability = null; } public ProjectElementAddedEvent(Component component) { this.attribute = null; this.component = component; this.capability = null; } public ProjectElementAddedEvent(Capability capability) { this.attribute = null; this.component = null; this.capability = capability; } /** Returns whether or not a new Attribute is associated with this event. */ public boolean isAttributeAddedEvent() { return attribute != null; } public Attribute getAttribute() { return attribute; } /** Returns whether or not a new Component is associated with this event. */ public boolean isComponentAddedEvent() { return component != null; } public Component getComponent() { return component; } /** Returns whether or not a new Capability is associated with this event. */ public boolean isCapabilityAddedEvent() { return capability != null; } public Capability getCapability() { return capability; } public static Type<ProjectElementAddedHandler> getType() { return TYPE; } @Override protected void dispatch(ProjectElementAddedHandler handler) { handler.onProjectElementAdded(this); } @Override public Type<ProjectElementAddedHandler> getAssociatedType() { return TYPE; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectElementAddedEvent.java
Java
asf20
2,991
// 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.client.event; import com.google.gwt.event.shared.EventHandler; /** * Event handler for {@link ProjectHasNoElementsEvent}. * * @author chrsmith@google.com (Chris Smith) */ public interface ProjectHasNoElementsHandler extends EventHandler { public void onProjectHasNoElements(ProjectHasNoElementsEvent event); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/event/ProjectHasNoElementsHandler.java
Java
asf20
977
// 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.client; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ChangeEvent; import com.google.gwt.event.shared.EventBus; import com.google.gwt.event.shared.SimpleEventBus; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiFactory; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.Widget; import com.google.testing.testify.risk.frontend.client.event.ProjectChangedEvent; import com.google.testing.testify.risk.frontend.client.event.ProjectChangedHandler; import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedEvent; import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedHandler; import com.google.testing.testify.risk.frontend.client.event.ProjectHasNoElementsEvent; import com.google.testing.testify.risk.frontend.client.event.ProjectHasNoElementsHandler; import com.google.testing.testify.risk.frontend.client.presenter.AttributesPresenter; import com.google.testing.testify.risk.frontend.client.presenter.BasePagePresenter; import com.google.testing.testify.risk.frontend.client.presenter.CapabilitiesPresenter; import com.google.testing.testify.risk.frontend.client.presenter.CapabilityDetailsPresenter; import com.google.testing.testify.risk.frontend.client.presenter.ComponentsPresenter; import com.google.testing.testify.risk.frontend.client.presenter.ConfigureDataPresenter; import com.google.testing.testify.risk.frontend.client.presenter.ConfigureFiltersPresenter; import com.google.testing.testify.risk.frontend.client.presenter.KnownRiskPresenter; import com.google.testing.testify.risk.frontend.client.presenter.ProjectSettingsPresenter; import com.google.testing.testify.risk.frontend.client.presenter.TaPagePresenter; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; import com.google.testing.testify.risk.frontend.client.view.impl.AttributesViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.CapabilitiesViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.CapabilityDetailsViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.ComponentsViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.ConfigureDataViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.ConfigureFiltersViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.KnownRiskViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.ProjectDataViewImpl; import com.google.testing.testify.risk.frontend.client.view.impl.ProjectSettingsViewImpl; import com.google.testing.testify.risk.frontend.client.view.widgets.NavigationLink; import com.google.testing.testify.risk.frontend.client.view.widgets.ProjectFavoriteStar; import com.google.testing.testify.risk.frontend.client.view.widgets.PageHeaderWidget; 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.UploadedDatum; 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.shared.rpc.DataRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync; import java.util.List; /** * The main application for Test Analytics. Contains the general view area which is populated * with pages that show data. * * @author jimr@google.com (Jim Reardon) */ public class TaApplication extends Composite { protected interface TestifyApplicationUiBinder extends UiBinder<Widget, TaApplication> {} private static final TestifyApplicationUiBinder uiBinder = GWT.create(TestifyApplicationUiBinder.class); @UiField protected SimplePanel contentPanel; @UiField protected ListBox userProjectsListBox; @UiField protected ProjectFavoriteStar projectFavoriteStar; @UiField protected Label projectNameLabel; @UiField protected NavigationLink projectDetailsLink; @UiField protected NavigationLink attributesLink; @UiField protected NavigationLink componentsLink; @UiField protected NavigationLink capabilitiesLink; @UiField protected NavigationLink configureDataLink; @UiField protected NavigationLink configureFiltersLink; @UiField protected NavigationLink projectBugsLink; @UiField protected NavigationLink projectCheckinsLink; @UiField protected NavigationLink projectTestcasesLink; @UiField protected NavigationLink knownRisksLink; // This link is treated differently because it does not show up in the sidebar. private NavigationLink capabilityDetailsLink = new NavigationLink("", -1, "capability-details", null); public static final String PAGE_HISTORY_TOKEN_CAPABILITY_DETAILS = "capability-details"; private final List<NavigationLink> allLinks; private Project project; private final ProjectRpcAsync projectService; private final UserRpcAsync userService; private final DataRpcAsync dataService; /** EventBus for firing and subscribing to application-level events. */ private final EventBus eventBus = new SimpleEventBus(); /** Current page the application is on. */ private NavigationLink currentLink; public TaApplication(Project project, ProjectRpcAsync projectService, UserRpcAsync userService, DataRpcAsync dataService) { this.projectService = projectService; this.userService = userService; this.dataService = dataService; initWidget(uiBinder.createAndBindUi(this)); allLinks = Lists.newArrayList( projectDetailsLink, attributesLink, componentsLink, capabilitiesLink, configureDataLink, configureFiltersLink, projectBugsLink, projectCheckinsLink, projectTestcasesLink, knownRisksLink, capabilityDetailsLink); setProject(project); initializeToolbar(); initializeMenuItems(); hookupEventListeners(); // Default page. switchToPage(projectDetailsLink, ""); } @UiFactory public PageHeaderWidget createTestifyPageHeaderWidget() { return new PageHeaderWidget(userService); } @UiHandler("userProjectsListBox") protected void onSelectNewProject(ChangeEvent event) { int selectedIndex = userProjectsListBox.getSelectedIndex(); History.newItem( "/" + userProjectsListBox.getValue(selectedIndex) + "/" + currentLink.getHistoryTokenName()); } /** * Initialize toolbar widgets; the project list box (which contains projects the user has * explicit access to or are starred) and the star for the current project. */ private void initializeToolbar() { final long currentProjectId = project.getProjectId(); // Add the current project as a place holder while we load other projects the user cares about. userProjectsListBox.addItem(project.getName()); projectService.queryUserProjects( new TaCallback<List<Project>>("querying projects") { @Override public void onSuccess(List<Project> result) { userProjectsListBox.clear(); // The first item in the list box is always the 'current' project. userProjectsListBox.addItem(project.getName(), project.getProjectId().toString()); for (Project p : result) { if (!p.getProjectId().equals(currentProjectId)) { userProjectsListBox.addItem(p.getName(), p.getProjectId().toString()); } } userProjectsListBox.setSelectedIndex(0); } }); // Initialize the project favorite star. projectFavoriteStar.attachToProject(project.getProjectId()); userService.getStarredProjects( new TaCallback<List<Long>>("retrieving starred projects") { @Override public void onSuccess(List<Long> result) { if (result.contains(project.getProjectId())) { projectFavoriteStar.setStarredStatus(true); } } }); // Initialize the project name. projectNameLabel.setText(project.getName()); } private void setProject(Project project) { this.project = project; } public Project getProject() { return project; } public void switchToPage(String historyToken, String pageData) { // If there's no page specified, switch to our default project details page. if (historyToken == null || "".equals(historyToken)) { switchToPage(projectDetailsLink, ""); return; } for (NavigationLink link : allLinks) { if (link.getHistoryTokenName().equals(historyToken)) { switchToPage(link, pageData); return; } } NotificationUtil.displayErrorMessage("The requested page is currently unavailable."); } /** * Switches the current view to the provided Testify application page. */ public void switchToPage(NavigationLink link, String pageData) { NavigationLink oldLink = currentLink; this.currentLink = link; if (oldLink != null) { oldLink.unSelect(); } link.select(); TaPagePresenter presenter = link.getPresenter(); if (presenter != null) { presenter.refreshView(pageData); setAsMainContent(presenter.getView()); } else { // No presenter means something went awry. NotificationUtil.displayErrorMessage("The requested page is currently unavailable."); } } /** Initializes machinery related to navigation via menu items. */ private void initializeMenuItems() { projectDetailsLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createProjectSettingsPage(); } }); attributesLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createAttributesPage(); } }); componentsLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createComponentsPage(); } }); capabilitiesLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createEditCapabilitiesPage(); } }); configureDataLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createConfigureDataPage(); } }); configureFiltersLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createFiltersPage(); } }); projectBugsLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createBugsPage(); } }); projectCheckinsLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createCheckinsPage(); } }); projectTestcasesLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createTestcasesPage(); } }); knownRisksLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createKnownRiskPage(); } }); capabilityDetailsLink.setCreatePresenterFunction(new Function<Void, TaPagePresenter>() { @Override public TaPagePresenter apply(Void input) { return createCapabilityDetailsPage(); } }); // Update menu item hyper links to include the project number. for (NavigationLink link : allLinks) { link.setProjectId(project.getProjectId()); } } /** * Subscribes top-level UI elements to application-level events. */ private void hookupEventListeners() { /** * Associate all navigation links with project stage. We can then enable or disable links based * on changes the user makes relative to their current project stage. */ final List<NavigationLink> needFullAccModel = Lists.newArrayList( configureDataLink, configureFiltersLink, projectTestcasesLink, projectBugsLink, projectCheckinsLink, knownRisksLink); // If the project has no elements associated with stage n, disable all links to stages after n. eventBus.addHandler(ProjectHasNoElementsEvent.getType(), new ProjectHasNoElementsHandler() { @Override public void onProjectHasNoElements(ProjectHasNoElementsEvent event) { // Disable capabilities link if we don't have both attributes and components. if (event.projectHasNoAttributes() || event.projectHasNoComponents()) { capabilitiesLink.disable(); } // If we're missing any ACC components, disable anything that requires a full model. if (event.projectHasNoAttributes() || event.projectHasNoCapabilities() || event.projectHasNoComponents()) { for (NavigationLink link : needFullAccModel) { link.disable(); } } } }); // If the project adds a new element, enable links to the next stage. eventBus.addHandler(ProjectElementAddedEvent.getType(), new ProjectElementAddedHandler() { @Override public void onProjectElementAdded(ProjectElementAddedEvent event) { if (event.isAttributeAddedEvent() || event.isComponentAddedEvent()) { capabilitiesLink.enable(); } else if (event.isCapabilityAddedEvent()) { for (NavigationLink link : needFullAccModel) { link.enable(); } } } }); } /** * Displays the widget on the main content panel. */ private void setAsMainContent(Widget widget) { if (widget != null) { contentPanel.clear(); contentPanel.setWidget(widget); } } /** * Initializes the Presenter and View for Project Settings. */ private TaPagePresenter createProjectSettingsPage() { ProjectSettingsViewImpl projectSettingsView = new ProjectSettingsViewImpl(); ProjectSettingsPresenter projectSettingsPresenter = new ProjectSettingsPresenter(project, projectService, userService, projectSettingsView, eventBus); // Hook into the Project Settings Presenter's ProjectChanged event. eventBus.addHandler(ProjectChangedEvent.getType(), new ProjectChangedHandler() { @Override public void onProjectChanged(ProjectChangedEvent event) { setProject(event.getProject()); initializeToolbar(); } }); return projectSettingsPresenter; } /** * Initializes the Presenter and View for Attributes page. */ private AttributesPresenter createAttributesPage() { AttributesViewImpl attributesView = new AttributesViewImpl(); AttributesPresenter attributesPresenter = new AttributesPresenter( project, projectService, userService, dataService, attributesView, eventBus); return attributesPresenter; } /** * Initializes the Presenter and View for the Components page. */ private ComponentsPresenter createComponentsPage() { ComponentsViewImpl componentsView = new ComponentsViewImpl(); ComponentsPresenter componentsPresenter = new ComponentsPresenter( project, projectService, userService, dataService, componentsView, eventBus); return componentsPresenter; } /** * Creates the tab which controls a Projects' Capabilities. */ private CapabilitiesPresenter createEditCapabilitiesPage() { CapabilitiesViewImpl capabilitiesView = new CapabilitiesViewImpl(); CapabilitiesPresenter capabilitiesPresenter = new CapabilitiesPresenter( project, projectService, userService, capabilitiesView, eventBus); return capabilitiesPresenter; } private CapabilityDetailsPresenter createCapabilityDetailsPage() { CapabilityDetailsViewImpl detailsView = new CapabilityDetailsViewImpl(); CapabilityDetailsPresenter capabilityDetailsPresenter = new CapabilityDetailsPresenter(project, projectService, dataService, userService, detailsView); return capabilityDetailsPresenter; } /** * Initializes the Presenter and View for the Configure Data page. */ private ConfigureDataPresenter createConfigureDataPage() { ConfigureDataViewImpl view = new ConfigureDataViewImpl(); ConfigureDataPresenter configureDataPresenter = new ConfigureDataPresenter(project, dataService, view); return configureDataPresenter; } private ConfigureFiltersPresenter createFiltersPage() { ConfigureFiltersViewImpl view = new ConfigureFiltersViewImpl(); ConfigureFiltersPresenter filtersPresenter = new ConfigureFiltersPresenter(project, dataService, projectService, view); return filtersPresenter; } /** * Returns a generic page presenter displaying the given view and performing the given * action when refreshView is called. */ private TaPagePresenter createPagePresenter( final Widget mainView, final Function<Void, Void> onRefreshView) { final Label emptyLabel = new Label(""); return new BasePagePresenter() { @Override public Widget getView() { return mainView; } @Override public void refreshView() { onRefreshView.apply(null); } }; } /** Initializes the Presenter and View for the Bugs page. */ private TaPagePresenter createBugsPage() { final Label emptyLabel = new Label(); final ProjectDataViewImpl dataView = new ProjectDataViewImpl(); dataView.setPageText( "Project Bugs", "The following bugs have been uploaded to your Test Analytics project."); Function<Void, Void> onRefreshPage = new Function<Void, Void>() { @Override public Void apply(Void input) { dataService.getProjectBugsById(getProject().getProjectId(), new TaCallback<List<Bug>>("querying project bugs") { @Override public void onSuccess(List<Bug> results) { List<UploadedDatum> converted = Lists.newArrayList(); for (Bug item : results) { converted.add(item); } dataView.displayData(converted); } }); return null; } }; // Start an initial request for project bugs. onRefreshPage.apply(null); TaPagePresenter projectBugsPresenter = createPagePresenter(dataView, onRefreshPage); return projectBugsPresenter; } /** Initializes the Presenter and View for the Checkins page. */ private TaPagePresenter createCheckinsPage() { final Label emptyLabel = new Label(); final ProjectDataViewImpl dataView = new ProjectDataViewImpl(); dataView.setPageText( "Project Checkins", "The following checkins have been uploaded to your Test Analytics project."); Function<Void, Void> onRefreshPage = new Function<Void, Void>() { @Override public Void apply(Void input) { dataService.getProjectCheckinsById(getProject().getProjectId(), new TaCallback<List<Checkin>>("querying project checkins") { @Override public void onSuccess(List<Checkin> results) { List<UploadedDatum> converted = Lists.newArrayList(); for (Checkin item : results) { converted.add(item); } dataView.displayData(converted); } }); return null; } }; // Start an initial request for project checkins. onRefreshPage.apply(null); TaPagePresenter projectCheckinsPresenter = createPagePresenter(dataView, onRefreshPage); return projectCheckinsPresenter; } /** Initializes the Presenter and View for the testcases page. */ private TaPagePresenter createTestcasesPage() { final Label emptyLabel = new Label(); final ProjectDataViewImpl dataView = new ProjectDataViewImpl(); dataView.setPageText( "Project Testcases", "The following testcases have been uploaded to your Test Analytics project."); Function<Void, Void> onRefreshPage = new Function<Void, Void>() { @Override public Void apply(Void input) { dataService.getProjectTestCasesById(getProject().getProjectId(), new TaCallback<List<TestCase>>("querying project testcases") { @Override public void onSuccess(List<TestCase> results) { List<UploadedDatum> converted = Lists.newArrayList(); for (TestCase item : results) { converted.add(item); } dataView.displayData(converted); } }); return null; } }; // Start an initial request for project testcases. onRefreshPage.apply(null); TaPagePresenter projectTestcasesPresenter = createPagePresenter(dataView, onRefreshPage); return projectTestcasesPresenter; } /** * Initialize the Presenter and View for the Known Risks page. */ private KnownRiskPresenter createKnownRiskPage() { KnownRiskViewImpl riskView = new KnownRiskViewImpl(); KnownRiskPresenter knownRiskPresenter = new KnownRiskPresenter(project, projectService, riskView); return knownRiskPresenter; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/TaApplication.java
Java
asf20
23,076
// 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.client.util; import com.google.common.collect.ImmutableList; import com.google.gwt.regexp.shared.MatchResult; import com.google.gwt.regexp.shared.RegExp; import java.util.List; /** * Helper functions for links. * * @author jimr@google.com (Jim Reardon) */ public class LinkUtil { private static final List<String> PROTOCOL_WHITELIST = ImmutableList.of("http", "https"); /** * Returns the domain of a link, for displaying next to link. Examples: * http://ourbugsoftware/1239123 -> [ourbugsoftware/] * http://testcases.example/mytest/1234 -> [testcases.example/] * * If the protocol isn't whitelisted (see PROTOCOL_WHITELIST) or the URL can't be parsed, * this will return null. * * @param link the full URL * @return the host of the URL. Null if protocol isn't in PROTOCOL_WHITELIST or URL can't be * parsed. */ public static String getLinkHost(String link) { if (link != null) { // It doesn't seem as if java.net.URL is GWT-friendly. Thus... GWT regular expressions! RegExp regExp = RegExp.compile("(\\w+?)://([\\-\\.\\w]+?)/.*"); // toLowerCase is okay because nothing we're interested in is case sensitive. MatchResult result = regExp.exec(link.toLowerCase()); if (result != null) { String protocol = result.getGroup(1); String host = result.getGroup(2); if (PROTOCOL_WHITELIST.contains(protocol)) { return "[" + host + "/]"; } } } return null; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/util/LinkUtil.java
Java
asf20
2,157
// 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.client.util; import com.google.gwt.user.client.ui.Label; import com.google.testing.testify.risk.frontend.client.view.widgets.StandardDialogBox; /** * Factory for displaying error messages on the client UI. * * @author chrsmith@google.com (Chris Smith) */ public class NotificationUtil { /** Disable construction. */ private NotificationUtil() {} /** Displays an error message generated from the given exception. */ public static void displayErrorMessage(Throwable exception) { displayErrorMessage("Unhandled Exception", exception); } /** Displays an error message with the given text. */ public static void displayErrorMessage(String errorText) { displayErrorMessage(errorText, null); } /** Displays an error message along with the provided exception information. */ public static void displayErrorMessage(String errorMessage, Throwable exception) { StandardDialogBox widget = new StandardDialogBox(); widget.setTitle("Oh snap! Test Analytics encountered an error."); widget.add(new Label(errorMessage)); if (exception != null) { StringBuilder exceptionMessageText = new StringBuilder(); exceptionMessageText.append("Exception of type: " + exception.getClass().getName()); exceptionMessageText.append("\n"); exceptionMessageText.append(exception.getMessage()); widget.add(new Label(exceptionMessageText.toString())); } StandardDialogBox.showAsDialog(widget); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/util/NotificationUtil.java
Java
asf20
2,118
// 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.client; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.testing.testify.risk.frontend.client.util.NotificationUtil; /** * General purpose async callback which routes failures to an error dialog. * * @author chrsmith@google.com (Chris Smith) * @param <T> The return type of the async callback. */ public class TaCallback<T> implements AsyncCallback<T> { private String asyncCallPurpose; public static TaCallback<Void> getNoopCallback() { return new TaCallback<Void>("generic action"); } /** * General purpose callback which handles failures by showing an error dialog. * * @param asyncCallPurpose the purpose of this call; showed in case of error, ie: * "Error " + asyncCallPurpose + "." followed by exception detail. */ public TaCallback(String asyncCallPurpose) { this.asyncCallPurpose = asyncCallPurpose; } /** On asynchronous failure, displays an error message to the user. */ @Override public void onFailure(Throwable caught) { NotificationUtil.displayErrorMessage( "Error " + asyncCallPurpose + ".", caught); } @Override public void onSuccess(T result) { } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/client/TaCallback.java
Java
asf20
1,818
// 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.shared.rpc; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; 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; /** * Interface for requesting data aggregation from an external source. * * @author chrsmith@google.com (Chris Smith) */ @RemoteServiceRelativePath("service/data") public interface DataRpc extends RemoteService { public List<DataSource> getDataSources(); public void setSignedOff(Long projectId, AccElementType type, Long elementId, boolean isSignedOff); public List<Signoff> getSignoffsByType(Long projectId, AccElementType type); public Boolean isSignedOff(AccElementType type, Long elementId); 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 updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<Checkin> getProjectCheckinsById(long projectId); public void addCheckin(Checkin checkin); public void updateCheckinAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<TestCase> getProjectTestCasesById(long projectId); public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId); public void addTestCase(TestCase testCase); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/DataRpc.java
Java
asf20
2,893
// 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.shared.rpc; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.google.testing.testify.risk.frontend.model.LoginStatus; import java.util.List; /** * Interface for updating user information between client and server. * * @author chrsmith@google.com (Chris Smith) */ @RemoteServiceRelativePath("service/user") public abstract interface UserRpc extends RemoteService { public boolean isDevMode(); public LoginStatus getLoginStatus(String returnUrl); public ProjectAccess getAccessLevel(long projectId); public boolean hasAdministratorAccess(); public boolean hasEditAccess(long projectId); public List<Long> getStarredProjects(); public void starProject(long projectId); public void unstarProject(long projectId); public enum ProjectAccess { ADMINISTRATOR_ACCESS, OWNER_ACCESS, EDIT_ACCESS, EXPLICIT_VIEW_ACCESS, VIEW_ACCESS, NO_ACCESS; /** Returns whether or not this access level can perform the specified access type. */ public boolean hasAccess(ProjectAccess testAccess) { return (this.ordinal() <= testAccess.ordinal()); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/UserRpc.java
Java
asf20
1,840
// 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.shared.rpc; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; 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; /** * Interface for updating project information between client and server. * * @author chrsmith@google.com (Chris Smith) */ @RemoteServiceRelativePath("service/project") public interface ProjectRpc extends RemoteService { public List<Project> query(String query); public List<Project> queryUserProjects(); public Project getProjectById(long projectId); public Long createProject(Project project); public void updateProject(Project project); public void removeProject(Project project); 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); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/ProjectRpc.java
Java
asf20
2,669
// 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.shared.rpc; import com.google.gwt.user.client.rpc.AsyncCallback; 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; /** * Interface for requesting data aggregation from an external source. * * @author chrsmith@google.com (Chris Smith) */ public interface DataRpcAsync { public void getDataSources(AsyncCallback<List<DataSource>> callback); public void setSignedOff(Long projectId, AccElementType type, Long elementId, boolean isSignedOff, AsyncCallback<Void> callback); public void isSignedOff(AccElementType type, Long elementId, AsyncCallback<Boolean> callback); public void getSignoffsByType(Long projectId, AccElementType type, AsyncCallback<List<Signoff>> callback); public void getProjectRequests(long projectId, AsyncCallback<List<DataRequest>> callback); public void addDataRequest(DataRequest request, AsyncCallback<Long> callback); public void updateDataRequest(DataRequest request, AsyncCallback<Void> callback); public void removeDataRequest(DataRequest request, AsyncCallback<Void> callback); public void getFilters(long projectId, AsyncCallback<List<Filter>> callback); public void addFilter(Filter filter, AsyncCallback<Long> callback); public void updateFilter(Filter filter, AsyncCallback<Void> callback); public void removeFilter(Filter filter, AsyncCallback<Void> callback); public void getProjectBugsById(long projectId, AsyncCallback<List<Bug>> callback); public void updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId, AsyncCallback<Void> callback); public void addBug(Bug bug, AsyncCallback<Void> callback); public void getProjectCheckinsById(long projectId, AsyncCallback<List<Checkin>> callback); public void updateCheckinAssociations(long checkinId, long attributeId, long componentId, long capabilityId, AsyncCallback<Void> callback); public void addCheckin(Checkin checkin, AsyncCallback<Void> callback); public void getProjectTestCasesById(long projectId, AsyncCallback<List<TestCase>> callback); public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId, AsyncCallback<Void> callback); public void addTestCase(TestCase testCase, AsyncCallback<Void> callback); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/DataRpcAsync.java
Java
asf20
3,407
// 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.shared.rpc; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; import com.google.testing.testify.risk.frontend.model.Project; /** * Interface for service which can create a test project. * * @author jimr@google.com (Jim Reardon) */ @RemoteServiceRelativePath("service/testprojectcreator") public interface TestProjectCreatorRpc extends RemoteService { public Project createTestProject(); public void createStandardDataSources(); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/TestProjectCreatorRpc.java
Java
asf20
1,167
// 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.shared.rpc; import com.google.gwt.user.client.rpc.AsyncCallback; 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; /** * Async interface for updating project information between client and server. * * @author chrsmith@google.com (Chris Smith) */ public interface ProjectRpcAsync { public void query(String query, AsyncCallback<List<Project>> callback); public void queryUserProjects(AsyncCallback<List<Project>> callback); public void getProjectById(long projectId, AsyncCallback<Project> callback); public void createProject(Project projInfo, AsyncCallback<Long> callback); public void updateProject(Project projInfo, AsyncCallback<Void> callback); public void removeProject(Project projInfo, AsyncCallback<Void> callback); public void getLabels(long projectId, AsyncCallback<List<AccLabel>> callback); public void getProjectAttributes(long projectId, AsyncCallback<List<Attribute>> callback); public void createAttribute(Attribute attribute, AsyncCallback<Long> callback); public void updateAttribute(Attribute attribute, AsyncCallback<Attribute> callback); public void removeAttribute(Attribute attribute, AsyncCallback<Void> callback); public void reorderAttributes(long projectId, List<Long> newOrder, AsyncCallback<Void> callback); public void getProjectComponents(long projectId, AsyncCallback<List<Component>> callback); public void createComponent(Component component, AsyncCallback<Long> callback); public void updateComponent(Component component, AsyncCallback<Component> callback); public void removeComponent(Component component, AsyncCallback<Void> callback); public void reorderComponents(long projectId, List<Long> newOrder, AsyncCallback<Void> callback); public void getCapabilityById(long projectId, long capabilityId, AsyncCallback<Capability> callback); public void getProjectCapabilities(long projectId, AsyncCallback<List<Capability>> callback); public void createCapability(Capability capability, AsyncCallback<Capability> callback); public void updateCapability(Capability capability, AsyncCallback<Void> callback); public void removeCapability(Capability capability, AsyncCallback<Void> callback); public void reorderCapabilities(long projectId, List<Long> newOrder, AsyncCallback<Void> callback); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/ProjectRpcAsync.java
Java
asf20
3,250
// 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.shared.rpc; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.testing.testify.risk.frontend.model.Project; /** * Async interface for {@link TestProjectCreatorRpc} * * @author jimr@google.com (Jim Reardon) */ public interface TestProjectCreatorRpcAsync { public void createTestProject(AsyncCallback<Project> callback); public void createStandardDataSources(AsyncCallback<Void> callback); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/TestProjectCreatorRpcAsync.java
Java
asf20
1,079
// 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.shared.rpc; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; /** * Async interface for updating user information between client and server. * * @author chrsmith@google.com (Chris Smith) */ public interface UserRpcAsync { public void isDevMode(AsyncCallback<Boolean> callback); public void getLoginStatus(String returnUrl, AsyncCallback<LoginStatus> callback); public void getAccessLevel(long projectId, AsyncCallback<ProjectAccess> callback); public void hasAdministratorAccess(AsyncCallback<Boolean> callback); public void hasEditAccess(long projectId, AsyncCallback<Boolean> callback); public void getStarredProjects(AsyncCallback<List<Long>> callback); public void starProject(long projectId, AsyncCallback<Void> callback); public void unstarProject(long projectId, AsyncCallback<Void> callback); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/rpc/UserRpcAsync.java
Java
asf20
1,661
// 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.shared.util; import com.google.testing.testify.risk.frontend.model.Capability; /** * Static utility class for calculating risk. * * @author jimr@google.com (Jim Reardon) */ public final class RiskUtil { /** Prevent instantiation. */ private RiskUtil() {} // COV_NF_LINE /** * Determine the individual risk value of the Capability. * * @return an arbitrary double value. Higher means riskier, lower means safer. It's range is * only meaningful when compared with other Capabilities' risk. */ public static double determineRisk(Capability capability) { double userImpact = capability.getUserImpact().getOrdinal() + 1; double failureRate = capability.getFailureRate().getOrdinal() + 1; if (userImpact < 0 || failureRate < 0) { return 0; } return (userImpact * failureRate) / 16.0; } // TODO(chrsmith): Think about and refactor this. Do we want to be more formal about our risk // calcluation? What is the underlying unit of risk? /** * Returns a string describing the estimated risk of the given capability. */ public static String getRiskText(Capability capability) { double risk = determineRisk(capability); if (risk > 0.75) { return "High"; } else if (risk > 0.25) { return "Medium"; } else if (risk > 0) { return "Low"; } else { return "n/a"; } } public static String getRiskExplanation(Capability capability) { return "User Impact: " + capability.getUserImpact().getDescription() + "; Failure Rate: " + capability.getFailureRate().getDescription(); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/util/RiskUtil.java
Java
asf20
2,256
// 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.shared.util; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import java.util.Collection; import java.util.List; /** * Common string functions. * * @author jimr@google.com (Jim Reardon) */ public class StringUtil { private static final Splitter UN_CSV = Splitter.on(",").trimResults().omitEmptyStrings(); private static final Joiner TO_CSV = Joiner.on(", ").skipNulls(); private StringUtil() {} // COV_NF_LINE public static List<String> csvToList(String string) { if (string == null) { return Lists.newArrayList(); } return Lists.newArrayList(UN_CSV.split(string)); } public static String listToCsv(Collection<String> strings) { return TO_CSV.join(strings); } /** * Properly trims and formats a CSV string, removing extra space or blank entries. * EG: "wer, wer,, wer" would turn into "wer, wer, wer". * * @param string the CSV string. * @return the re-formatted string. */ public static String trimAndReformatCsv(String string) { return listToCsv(csvToList(string)); } /** * Trims a string down to 500 characters. Ellipses will be added if truncated. * * @return text trimmed to 500 characters. */ public static String trimString(String inputText) { if (inputText.length() <= 500) { return inputText; } return inputText.subSequence(0, 497) + "..."; } /** * Returns items that are in a, but not in b. * * @param a the first list. * @param b the second list. * @return elements in a that are not in b. */ public static List<String> subtractList(List<String> a, List<String> b) { List<String> result = Lists.newArrayList(); for (String inA : a) { if (!b.contains(inA)) { result.add(inA); } } return result; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/shared/util/StringUtil.java
Java
asf20
2,517
// 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.servlet.ServletModule; import com.google.testing.testify.risk.frontend.server.api.impl.DataApiImpl; import com.google.testing.testify.risk.frontend.server.api.impl.UploadApiImpl; import com.google.testing.testify.risk.frontend.server.filter.WhitelistFilter; import com.google.testing.testify.risk.frontend.server.rpc.impl.DataRpcImpl; import com.google.testing.testify.risk.frontend.server.rpc.impl.ProjectRpcImpl; import com.google.testing.testify.risk.frontend.server.rpc.impl.TestProjectCreatorRpcImpl; import com.google.testing.testify.risk.frontend.server.rpc.impl.UserRpcImpl; import com.google.testing.testify.risk.frontend.server.task.UploadDataTask; /** * Guice module to inject servlets. This maps URLs (the first part of the map) to classes (the * second). * * Note guice servlets must be singletons. * * @author jimr@google.com (Jim Reardon) */ public class GuiceServletModule extends ServletModule { @Override protected void configureServlets() { // GWT services. serve("/service/project").with(ProjectRpcImpl.class); serve("/service/user").with(UserRpcImpl.class); serve("/service/data").with(DataRpcImpl.class); serve("/service/testprojectcreator").with(TestProjectCreatorRpcImpl.class); // The external API. serve("/api/data").with(DataApiImpl.class); serve("/api/upload").with(UploadApiImpl.class); // Administrative tasks, migration tasks, and crons. These must be locked down to admin // only rights, because they may allow user impersonation. serve("/_tasks/upload").with(UploadDataTask.class); // Do not filter special pages, like /_tasks/ or /_cron/, which are already protected as // admin-only through web.xml. This allows crons/tasks to run. filterRegex("/[^_].*", "/$").through(WhitelistFilter.class); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/GuiceServletModule.java
Java
asf20
2,499
// 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()); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/GuiceServletConfig.java
Java
asf20
1,300
// 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); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/ProjectService.java
Java
asf20
2,571
// 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); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/DataService.java
Java
asf20
2,891
// 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); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/impl/ProjectServiceImpl.java
Java
asf20
34,229
// 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; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/impl/DataServiceImpl.java
Java
asf20
18,919
// 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(); } } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/impl/UserServiceImpl.java
Java
asf20
11,842
// 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); }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/service/UserService.java
Java
asf20
2,138
// 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; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/InsufficientPrivlegesException.java
Java
asf20
1,168
// 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); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/rpc/impl/UserRpcImpl.java
Java
asf20
2,238
// 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); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/rpc/impl/ProjectRpcImpl.java
Java
asf20
4,596
// 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; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/rpc/impl/TestProjectCreatorRpcImpl.java
Java
asf20
14,753
// 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); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/rpc/impl/DataRpcImpl.java
Java
asf20
4,668
// 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); } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/GuiceProviderModule.java
Java
asf20
2,225
// 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; } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/task/UploadDataTask.java
Java
asf20
5,058
// 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) { } }
11shubhanjali-test
testanalytics_frontend/src/main/java/com/google/testing/testify/risk/frontend/server/filter/WhitelistFilter.java
Java
asf20
2,342