code
stringlengths
3
1.18M
language
stringclasses
1 value
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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"); } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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()); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } } } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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()); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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()); } } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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"); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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>(); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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) { } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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()); } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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(); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.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; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; import com.google.inject.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); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; /** * This creates a Guice injector which will be used to inject servlets and classes. * * @author jimr@google.com (Jim Reardon) */ public class GuiceServletConfig extends GuiceServletContextListener { /** * Create and return a Guice injector. * * @see com.google.inject.servlet.GuiceServletContextListener#getInjector() */ @Override protected Injector getInjector() { return Guice.createInjector( new GuiceProviderModule(), new GuiceServletModule()); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Project; import java.util.List; /** * Server service for accessing project information. * * @author jimr@google.com (Jim Reardon) */ public interface ProjectService { public List<Project> query(String query); public List<Project> queryUserProjects(); public List<Project> queryProjectsUserHasEditAccessTo(); public Project getProjectById(long id); public Project getProjectByName(String name); public Long createProject(Project projInfo); public void updateProject(Project projInfo); public void removeProject(Project projInfo); public List<AccLabel> getLabels(long projectId); public List<Attribute> getProjectAttributes(long projectId); public Long createAttribute(Attribute attribute); public Attribute updateAttribute(Attribute attribute); public void removeAttribute(Attribute attribute); public void reorderAttributes(long projectId, List<Long> newOrder); public List<Component> getProjectComponents(long projectId); public Long createComponent(Component component); public Component updateComponent(Component component); public void removeComponent(Component component); public void reorderComponents(long projectId, List<Long> newOrder); public Capability getCapabilityById(long projectId, long capabilityId); public List<Capability> getProjectCapabilities(long projectId); public Capability createCapability(Capability capability); public void updateCapability(Capability capability); public void removeCapability(Capability capability); public void reorderCapabilities(long projectId, List<Long> newOrder); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import java.util.List; /** * Server service for accessing data related to a project (ie; Bugs, Tests). * * @author jimr@google.com (Jim Reardon) */ public interface DataService { public boolean isSignedOff(AccElementType type, Long elementId); public void setSignedOff(long projectId, AccElementType type, long elementId, boolean isSignedOff); public List<Signoff> getSignoffsByType(long projectId, AccElementType type); public List<DataSource> getDataSources(); public List<DataRequest> getProjectRequests(long projectId); public long addDataRequest(DataRequest request); public void updateDataRequest(DataRequest request); public void removeDataRequest(DataRequest request); public List<Filter> getFilters(long projectId); public long addFilter(Filter filter); public void updateFilter(Filter filter); public void removeFilter(Filter filter); public List<Bug> getProjectBugsById(long projectId); public void addBug(Bug bug); public void addBug(Bug bug, String asEmail); public void updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<Checkin> getProjectCheckinsById(long projectId); public void addCheckin(Checkin checkin); public void addCheckin(Checkin checkin, String asEmail); public void updateCheckinAssociations(long bugId, long attributeId, long componentId, long capabilityId); public List<TestCase> getProjectTestCasesById(long projectId); public void addTestCase(TestCase testCase); public void addTestCase(TestCase testCase, String asEmail); public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.common.base.Function; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.HasLabels; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * This acts as a broker for the client when accessing project information, such as Attributes and * Components. Any operation will be checked using the user's current credentials, and fail if the * user doesn't have access to view or edit any project information. * * @author chrsmith@google.com (Chris Smith) */ @Singleton public class ProjectServiceImpl implements ProjectService { private static final Logger log = Logger.getLogger(ProjectServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final UserService userService; /** * Creates a new ProjectServiceImpl instance. Internally all methods will use the * PersistanceManager associated with JDOHelper.getPersistenceManagerFactory (meaning * jdoconfig.xml). */ @Inject public ProjectServiceImpl(PersistenceManagerFactory pmf, UserService userService) { this.pmf = pmf; this.userService = userService; } @SuppressWarnings("unchecked") @Override public List<Project> query(String query) { log.info("Querying: " + query); PersistenceManager pm = pmf.getPersistenceManager(); // TODO(jimr): this currently does not do a query, it just returns all public projects. Query jdoQuery = pm.newQuery(Project.class); jdoQuery.setOrdering("projectId asc"); List<Project> results = null; try { List<Project> returnedProjects = (List<Project>) jdoQuery.execute(); List<Project> safeToDisplayProjs = Lists.newArrayList(); for (Project returnedProject : returnedProjects) { if (userService.hasViewAccess(returnedProject)) { safeToDisplayProjs.add(returnedProject); } } results = ServletUtils.makeGwtSafe(safeToDisplayProjs, pm); populateCachedAccess(results); } finally { pm.close(); } return results; } private void populateCachedAccess(List<Project> projects) { for (Project p : projects) { populateCachedAccess(p); } } private void populateCachedAccess(Project p) { p.setCachedAccessLevel(userService.getAccessLevel(p)); } /** * Retrieves the list of projects relevant to the currently logged in user. */ @SuppressWarnings("unchecked") @Override public List<Project> queryUserProjects() { if (!userService.isUserLoggedIn()) { log.info("Querying user projects; user is not logged in."); return Lists.newArrayList(); } log.info("Querying user projects."); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Project.class); jdoQuery.setOrdering("projectId asc"); List<Project> results = null; try { List<Long> starredProjects = userService.getStarredProjects(); List<Project> returnedProjects = (List<Project>) jdoQuery.execute(); List<Project> projectsToReturn = Lists.newArrayList(); for (Project returnedProject : returnedProjects) { // Only returns the projects that are either: // * Starred by the user and have access (implicit or explicit). // * Granted VIEW or EDIT access explicitly. (Ignore public projects.) ProjectAccess access = userService.getAccessLevel(returnedProject); // If explicit, add it. Otherwise, check starred access (and implicit access). if (access.hasAccess(ProjectAccess.EXPLICIT_VIEW_ACCESS)) { projectsToReturn.add(returnedProject); } else if (access.hasAccess(ProjectAccess.VIEW_ACCESS) && starredProjects.contains(returnedProject.getProjectId())) { projectsToReturn.add(returnedProject); } } results = ServletUtils.makeGwtSafe(projectsToReturn, pm); populateCachedAccess(results); } finally { pm.close(); } return results; } /** * Returns the list of projects the currently logged in user has EDIT access to. */ @Override public List<Project> queryProjectsUserHasEditAccessTo() { ServletUtils.requireAccess(userService.isUserLoggedIn()); // Start with all starred projects and those granting explicit access. List<Project> projects = queryUserProjects(); List<Project> projectsToReturn = Lists.newArrayList(); for (Project project : projects) { if (userService.hasEditAccess(project)) { projectsToReturn.add(project); } } populateCachedAccess(projectsToReturn); return projectsToReturn; } @Override public Project getProjectById(long id) { log.info("Getting project: " + Long.toString(id)); PersistenceManager pm = pmf.getPersistenceManager(); try { Project retrievedProject = pm.getObjectById(Project.class, id); // Don't disclose that the project even exists if they don't have view access. if (retrievedProject != null && userService.hasViewAccess(retrievedProject)) { retrievedProject = ServletUtils.makeGwtSafe(retrievedProject, pm); populateCachedAccess(retrievedProject); return retrievedProject; } } finally { pm.close(); } return null; } @Override @SuppressWarnings("unchecked") public Project getProjectByName(String name) { log.info("Getting project with name: " + name); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Project.class); jdoQuery.declareParameters("String projectNameParam"); jdoQuery.setFilter("name == projectNameParam"); try { List<Project> returnedProjects = (List<Project>) jdoQuery.execute(name); log.info(String.format("Found %s projects with name %s", returnedProjects.size(), name)); for (Project target : returnedProjects) { if (userService.hasViewAccess(target)) { target = ServletUtils.makeGwtSafe(target, pm); populateCachedAccess(target); return target; } } } finally { pm.close(); } return null; } @Override public Long createProject(Project projInfo) { // The user must be logged in to create a project. ServletUtils.requireAccess(userService.isUserLoggedIn()); log.info("Creating new Project with name: " + projInfo.getName()); if (projInfo.getProjectId() != null) { throw new IllegalArgumentException( "You can only create a project with a null ID."); } PersistenceManager pm = pmf.getPersistenceManager(); try { // Automatically add the current user as an OWNER for the project. projInfo.addProjectOwner(userService.getEmail()); pm.makePersistent(projInfo); } finally { pm.close(); } return projInfo.getProjectId(); } @Override public void updateProject(Project projInfo) { if (projInfo.getProjectId() == null) { throw new IllegalArgumentException( "projInfo has not been saved. Please call createProject first."); } ServletUtils.requireAccess(userService.hasEditAccess(projInfo.getProjectId())); log.info("Updating Project: " + projInfo.getProjectId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); Project oldProject; try { oldProject = pm.getObjectById(Project.class, projInfo.getProjectId()); List<String> oldOwners = oldProject.getProjectOwners(); List<String> oldEditors = oldProject.getProjectEditors(); List<String> oldViewers = oldProject.getProjectViewers(); // If they're not an owner, keep the old list of owners around. if (!userService.hasOwnerAccess(projInfo.getProjectId())) { projInfo.setIsPubliclyVisible(oldProject.getIsPubliclyVisible()); projInfo.setProjectOwners(oldProject.getProjectOwners()); } pm.makePersistent(projInfo); log.info("Notifying users of any changes to access level"); String from = userService.getEmail(); List<String> added = StringUtil.subtractList(projInfo.getProjectOwners(), oldOwners); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "owner", projInfo.getName(), projInfo.getProjectId().toString()); } List<String> removed = StringUtil.subtractList(oldOwners, projInfo.getProjectOwners()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "owner", projInfo.getName(), projInfo.getProjectId().toString()); } added = StringUtil.subtractList(projInfo.getProjectEditors(), oldEditors); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "editor", projInfo.getName(), projInfo.getProjectId().toString()); } removed = StringUtil.subtractList(oldEditors, projInfo.getProjectEditors()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "editor", projInfo.getName(), projInfo.getProjectId().toString()); } added = StringUtil.subtractList(projInfo.getProjectViewers(), oldViewers); if (added.size() > 0) { ServletUtils.notifyAddedAccess(from, added, "viewer", projInfo.getName(), projInfo.getProjectId().toString()); } removed = StringUtil.subtractList(oldViewers, projInfo.getProjectViewers()); if (removed.size() > 0) { ServletUtils.notifyRemovedAccess(from, removed, "viewer", projInfo.getName(), projInfo.getProjectId().toString()); } } finally { pm.close(); } } @Override public void removeProject(Project projInfo) { if (projInfo.getProjectId() == null) { log.info("Attempting to delete unsaved project. Ignoring."); return; } ServletUtils.requireAccess(userService.hasOwnerAccess(projInfo.getProjectId())); PersistenceManager pm = pmf.getPersistenceManager(); try { Project projToDelete = pm.getObjectById(Project.class, projInfo.getProjectId()); // TODO(jimr): This delete could succeed but successive removes might fail, leaving dangling // data. We should retry or do something to assure complete destruction. // TODO(jimr): Undo? pm.deletePersistent(projToDelete); // Delete any child attributes, components, or capabilities. removeObjectsWithFieldValue(pm, Attribute.class, "parentProjectId", projInfo.getProjectId()); removeObjectsWithFieldValue(pm, Component.class, "parentProjectId", projInfo.getProjectId()); removeObjectsWithFieldValue(pm, Capability.class, "parentProjectId", projInfo.getProjectId()); // TODO(chrsmith): What about enabled data providers? For example, bugs or checkin data // associated with this project? We need to clear those out as well. } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<AccLabel> getLabels(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting labels for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(AccLabel.class); jdoQuery.setFilter("projectId == projectIdParam"); jdoQuery.declareParameters("Long projectIdParam"); try { List<AccLabel> labels = (List<AccLabel>) jdoQuery.execute(projectId); return ServletUtils.makeGwtSafe(labels, pm); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Attribute> getProjectAttributes(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Attributes for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Attribute.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Attribute> returnedAttributes = (List<Attribute>) jdoQuery.execute(projectId); returnedAttributes = ServletUtils.makeGwtSafe(returnedAttributes, pm); populateLabels(returnedAttributes, pm); return returnedAttributes; } finally { pm.close(); } } /** * Populates labels for a HasLabels item. * * @param <T> An object that HasLabels. * @param item The item to get labels for. * @param pm A persistence manager object. */ private <T extends HasLabels> void populateLabels(T item, PersistenceManager pm) { item.setAccLabels(getLabelsForItem(item, pm)); } /** * Populates labels for a list of HasLabels items. All items MUST be for the same project * and of the same type (ie, all Attributes). * * IMPORTANT: you probably want to detach your object before calling this. * * @param <T> An object that HasLabels. * @param items The items to get labels for. * @param pm A persistence manager object. */ @SuppressWarnings("unchecked") private <T extends HasLabels> void populateLabels(List<T> items, PersistenceManager pm) { if (items.size() > 0) { Map<Long, T> idToItem = Maps.newHashMap(); for (T item : items) { idToItem.put(item.getId(), item); } T item = items.get(0); AccElementType type = item.getElementType(); Long parentProjectId = item.getParentProjectId(); Query query = pm.newQuery(AccLabel.class); query.declareParameters("AccElementType elementTypeParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && projectId == projectIdParam"); List<AccLabel> labels = (List<AccLabel>) query.execute(type, parentProjectId); log.info("Found labels: " + labels.size()); for (AccLabel label : labels) { item = idToItem.get(label.getElementId()); if (item != null) { log.info("Putting label where it belongs: " + label.getLabelText()); item.addLabel(label); } } } } @SuppressWarnings("unchecked") private <T extends HasLabels> List<AccLabel> getLabelsForItem(T item, PersistenceManager pm) { Query query = pm.newQuery(AccLabel.class); query.declareParameters( "AccElementType elementTypeParam, Long elementIdParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && elementId == elementIdParam && " + "projectId == projectIdParam"); List<AccLabel> labels = (List<AccLabel>) query.execute(item.getElementType(), item.getId(), item.getParentProjectId()); // This constructs a new, real list -- the list returned by the above execution is a lazy-loaded // streaming query. That doesn't serialize. return Lists.newArrayList(labels); } /** * Saves labels for an item. * * This is not extremely necessary, but for simplicity ('always call persistLabels') it's here. * * @param <T> An object that HasLabels. * @param item The item to save the labels for. * @param pm A persistence mananger. */ private <T extends HasLabels> void persistLabels(T item, PersistenceManager pm) { List<AccLabel> toDelete = Lists.newArrayList(); Set<String> newLabelKeys = Sets.newHashSet(); for (AccLabel label : item.getAccLabels()) { if (label.getId() != null) { newLabelKeys.add(label.getId()); } } List<AccLabel> currentLabels = getLabelsForItem(item, pm); for (AccLabel label : currentLabels) { if (!newLabelKeys.contains(label.getId())) { toDelete.add(label); } } pm.deletePersistentAll(toDelete); // And add the new ones. pm.makePersistentAll(item.getAccLabels()); } private <T extends HasLabels> void updateLabelElementIds(T item, Long id) { for (AccLabel label : item.getAccLabels()) { label.setElementId(id); } } private <T extends HasLabels> void deleteLabels(T item, PersistenceManager pm) { pm.deletePersistentAll(item.getAccLabels()); } @Override public Long createAttribute(Attribute attribute) { ServletUtils.requireAccess(userService.hasEditAccess(attribute.getParentProjectId())); if (attribute.getAttributeId() != null) { throw new IllegalArgumentException( "You can only create an attribute with a null ID."); } log.info("Creating new Attribute with name: " + attribute.getName()); attribute.setName(attribute.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(attribute); // If we have labels, update their element ID now that we have an ID. if (attribute.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(attribute, attribute.getAttributeId()); pm = pmf.getPersistenceManager(); persistLabels(attribute, pm); } } finally { pm.close(); } return attribute.getAttributeId(); } @Override public Attribute updateAttribute(Attribute attribute) { if (attribute.getAttributeId() == null) { throw new IllegalArgumentException( "attribute has not been saved. Please call createAttribute first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(attribute.getParentProjectId())); log.info("Updating Attribute: " + attribute.getAttributeId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Attribute oldAttribute = pm.getObjectById(Attribute.class, attribute.getAttributeId()); if (oldAttribute.getParentProjectId() != attribute.getParentProjectId()) { log.severe("Possible attack -- attribute sent in and attribute being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } persistLabels(attribute, pm); pm.makePersistent(attribute); attribute = ServletUtils.makeGwtSafe(attribute, pm); populateLabels(attribute, pm); attribute.setAccLabels(ServletUtils.makeGwtSafe(attribute.getAccLabels(), pm)); return attribute; } finally { pm.close(); } } @Override public void removeAttribute(Attribute attribute) { if (attribute.getAttributeId() == null) { log.info("Attempting to delete unsaved Attribute. Ignoring."); return; } log.info("Removing Attribute: " + attribute.getAttributeId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Attribute attributeToDelete = pm.getObjectById(Attribute.class, attribute.getAttributeId()); ServletUtils.requireAccess(userService.hasEditAccess(attributeToDelete.getParentProjectId())); pm.deletePersistent(attributeToDelete); deleteLabels(attribute, pm); // Delete any child capabilities. removeObjectsWithFieldValue(pm, Capability.class, "attributeId", attribute.getAttributeId()); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public void reorderAttributes(long projectId, List<Long> newOrdering) { log.info("Reordering Attributes for project: " + Long.toString(projectId)); Function<Attribute, Long> getId = new Function<Attribute, Long>() { @Override public Long apply(Attribute input) { return input.getAttributeId(); } }; Setter<Attribute> setId = new Setter<Attribute>() { @Override public boolean apply(Attribute input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Attribute.class, newOrdering, getId, setId); } @SuppressWarnings("unchecked") @Override public List<Component> getProjectComponents(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Components for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Component.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Component> returnedComponents = (List<Component>) jdoQuery.execute(projectId); returnedComponents = ServletUtils.makeGwtSafe(returnedComponents, pm); populateLabels(returnedComponents, pm); return returnedComponents; } finally { pm.close(); } } @Override public Long createComponent(Component component) { ServletUtils.requireAccess(userService.hasEditAccess(component.getParentProjectId())); if (component.getComponentId() != null) { throw new IllegalArgumentException( "You can only create a component with a null ID."); } log.info("Creating new Component with name: " + component.getName()); component.setName(component.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(component); // If we have labels, update their element ID now that we have an ID. if (component.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(component, component.getId()); pm = pmf.getPersistenceManager(); persistLabels(component, pm); } } finally { pm.close(); } return component.getComponentId(); } @Override public Component updateComponent(Component component) { if (component.getComponentId() == null) { throw new IllegalArgumentException( "component has not been saved. Please call createComponent first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(component.getParentProjectId())); log.info("Updating Component: " + component.getComponentId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Component oldComponent = pm.getObjectById(Component.class, component.getComponentId()); if (oldComponent.getParentProjectId() != component.getParentProjectId()) { log.severe("Possible attack -- component sent in and component being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } persistLabels(component, pm); pm.makePersistent(component); component = ServletUtils.makeGwtSafe(component, pm); populateLabels(component, pm); component.setAccLabels(ServletUtils.makeGwtSafe(component.getAccLabels(), pm)); return component; } finally { pm.close(); } } @Override public void removeComponent(Component component) { if (component.getComponentId() == null) { log.info("Attempting to delete unsaved Component. Ignoring."); return; } log.info("Removing Component: " + component.getComponentId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Component componentToDelete = pm.getObjectById(Component.class, component.getComponentId()); ServletUtils.requireAccess(userService.hasEditAccess(componentToDelete.getParentProjectId())); pm.deletePersistent(componentToDelete); deleteLabels(componentToDelete, pm); // Delete any child capabilities. removeObjectsWithFieldValue(pm, Capability.class, "componentId", component.getComponentId()); } finally { pm.close(); } } @SuppressWarnings("unchecked") private <T> void setOrder(long projectId, Class<T> clazz, List<Long> order, Function<T, Long> getId, Setter<T> applyOrder) { log.info("setOrder executing with " + order.size() + " items passed in."); ServletUtils.requireAccess(userService.hasEditAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Query jdoQuery = pm.newQuery(clazz); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.declareParameters("Long parentProjectParam"); List<T> items = (List<T>) jdoQuery.execute(projectId); Map<Long, Integer> lookup = Maps.newHashMap(); for (int i = 0; i < order.size(); i++) { Long id = order.get(i); lookup.put(id, i); } for (T item : items) { Long id = getId.apply(item); Integer newIndex = lookup.get(id); if (newIndex != null) { if (applyOrder.apply(item, newIndex)) { pm.makePersistent(item); } } else { log.warning("Project contains item not covered in new ordering - ID: " + id); } } } finally { pm.close(); } log.info("setOrder complete"); } @Override public void reorderCapabilities(long projectId, List<Long> newOrdering) { log.info("Reordering capabilities for project: " + Long.toString(projectId)); Function<Capability, Long> getId = new Function<Capability, Long>() { @Override public Long apply(Capability input) { return input.getCapabilityId(); } }; Setter<Capability> setId = new Setter<Capability>() { @Override public boolean apply(Capability input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Capability.class, newOrdering, getId, setId); } @SuppressWarnings("unchecked") @Override public void reorderComponents(long projectId, List<Long> newOrdering) { log.info("Reordering Components for project: " + Long.toString(projectId)); Function<Component, Long> getId = new Function<Component, Long>() { @Override public Long apply(Component input) { return input.getComponentId(); } }; Setter<Component> setId = new Setter<Component>() { @Override public boolean apply(Component input, long value) { if (input.getDisplayOrder() != value) { input.setDisplayOrder(value); return true; } return false; } }; setOrder(projectId, Component.class, newOrdering, getId, setId); } private interface Setter<F> { boolean apply(F input, long value); } @Override @SuppressWarnings("unchecked") public Capability getCapabilityById(long projectId, long capabilityId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting capability for project by id: " + Long.toString(projectId) + ", " + Long.toString(capabilityId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Capability.class); jdoQuery.setFilter( "parentProjectId == parentProjectParam && capabilityId == capabilityIdParam"); jdoQuery.declareParameters("Long parentProjectParam, Long capabilityIdParam"); try { List<Capability> results = (List<Capability>) jdoQuery.execute( projectId, capabilityId); if (results.size() > 0) { Capability c = results.get(0); c = ServletUtils.makeGwtSafe(c, pm); populateLabels(c, pm); return c; } else { return null; } } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Capability> getProjectCapabilities(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Capabilities for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Capability.class); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("displayOrder asc"); jdoQuery.declareParameters("Long parentProjectParam"); try { List<Capability> returnedCapabilities = (List<Capability>) jdoQuery.execute(projectId); returnedCapabilities = ServletUtils.makeGwtSafe(returnedCapabilities, pm); populateLabels(returnedCapabilities, pm); return returnedCapabilities; } finally { pm.close(); } } @Override public Capability createCapability(Capability capability) { ServletUtils.requireAccess(userService.hasEditAccess(capability.getParentProjectId())); if (capability.getCapabilityId() != null) { throw new IllegalArgumentException( "You can only create a capability with a null ID."); } log.info("Creating new Capability with name: " + capability.getName()); capability.setName(capability.getName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(capability); capability = ServletUtils.makeGwtSafe(capability, pm); // If we have labels, update their element ID now that we have an ID. if (capability.getAccLabels().size() > 0) { pm.close(); updateLabelElementIds(capability, capability.getId()); pm = pmf.getPersistenceManager(); persistLabels(capability, pm); } return capability; } finally { pm.close(); } } @Override public void updateCapability(Capability capability) { if (capability.getCapabilityId() == null) { throw new IllegalArgumentException( "Capability has not been saved. Please call createCapability first."); } // Make sure they can edit the project into which they are trying to save. ServletUtils.requireAccess(userService.hasEditAccess(capability.getParentProjectId())); log.info("Updating capability: " + capability.getCapabilityId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Capability oldCapability = pm.getObjectById(Capability.class, capability.getCapabilityId()); if (oldCapability.getParentProjectId() != capability.getParentProjectId()) { log.severe("Possible attack -- capability sent in and capability being overwritten had" + " different project IDs."); ServletUtils.requireAccess(false); } pm.makePersistent(capability); persistLabels(capability, pm); } finally { pm.close(); } } @Override public void removeCapability(Capability capability) { if (capability.getCapabilityId() == null) { log.info("Attempting to delete unsaved Component. Ignoring."); return; } log.info("Removing Capability: " + capability.getCapabilityId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Capability capabilityToDelete = pm.getObjectById( Capability.class, capability.getCapabilityId()); ServletUtils.requireAccess(userService.hasEditAccess( capabilityToDelete.getParentProjectId())); pm.deletePersistent(capabilityToDelete); deleteLabels(capabilityToDelete, pm); } finally { pm.close(); } } /** * Deletes all stored objects of the given type with the field matching the specified ID. * Primarily this is used for deleting dependent, child objects when the parent is removed. * * @param pm the PersistenceManager used to perform the deletion operation. * @param type the type of the object to be removed. * @param fieldName the name on the object to check. * @param fieldValue the value which must match in order for the object to get deleted. */ private <T> void removeObjectsWithFieldValue( PersistenceManager pm, Class<T> type, String fieldName, long fieldValue) throws IllegalArgumentException { // Do a brief sanity check on the field name. fieldName = fieldName.trim(); if ((fieldName.contains(" ")) || (fieldName.contains(";"))) { throw new IllegalArgumentException(); } StringBuilder message = new StringBuilder(); message.append("Deleting all "); message.append(type.getCanonicalName()); message.append(" with '"); message.append(fieldName); message.append("' equal to "); message.append(Long.toString(fieldValue)); log.info(message.toString()); Query objectsToDeleteQuery = pm.newQuery(type); objectsToDeleteQuery.setFilter(fieldName + " == fieldValueParam"); objectsToDeleteQuery.declareParameters("int fieldValueParam"); objectsToDeleteQuery.deletePersistentAll(fieldValue); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.DatumType; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.model.UploadedDatum; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * Implementation of the DataRequestService, for tracking project requests for external * data. This data is also exposed via the DataRequest servlet. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ @Singleton public class DataServiceImpl implements DataService { private static final Logger log = Logger.getLogger(DataServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final UserService userService; /** * Creates a new DataServiceImpl instance. */ @Inject public DataServiceImpl(PersistenceManagerFactory pmf, UserService userService) { this.pmf = pmf; this.userService = userService; } @Override public boolean isSignedOff(AccElementType type, Long elementId) { Signoff signoff = getSignoff(type, elementId); return signoff == null ? false : signoff.getSignedOff(); } @Override public void setSignedOff(long projectId, AccElementType type, long elementId, boolean isSignedOff) { ServletUtils.requireAccess(userService.hasEditAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Signoff signoff = getSignoff(type, elementId); if (signoff == null) { signoff = new Signoff(); signoff.setParentProjectId(projectId); signoff.setElementType(type); signoff.setElementId(elementId); } else { if (signoff.getParentProjectId() != projectId) { ServletUtils.requireAccess(false); } } signoff.setSignedOff(isSignedOff); pm.makePersistent(signoff); } finally { pm.close(); } } @Override @SuppressWarnings("unchecked") public List<Signoff> getSignoffsByType(long projectId, AccElementType type) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); try { Query query = pm.newQuery(Signoff.class); query.declareParameters("AccElementType elementTypeParam, Long projectIdParam"); query.setFilter("elementType == elementTypeParam && parentProjectId == projectIdParam"); List<Signoff> results = (List<Signoff>) query.execute(type, projectId); return ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } } @SuppressWarnings("unchecked") private Signoff getSignoff(AccElementType type, Long elementId) { PersistenceManager pm = pmf.getPersistenceManager(); try { Query query = pm.newQuery(Signoff.class); query.declareParameters("AccElementType elementTypeParam, Long elementIdParam"); query.setFilter("elementType == elementTypeParam && elementId == elementIdParam"); List<Signoff> results = (List<Signoff>) query.execute(type, elementId); if (results.size() > 0) { Signoff signoff = results.get(0); ServletUtils.requireAccess(userService.hasViewAccess(signoff.getParentProjectId())); return ServletUtils.makeGwtSafe(signoff, pm); } else { return null; } } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<DataSource> getDataSources() { boolean isInternal = userService.isInternalUser(); PersistenceManager pm = pmf.getPersistenceManager(); List<DataSource> results = null; log.info("Retrieving data sources."); try { Query query = pm.newQuery(DataSource.class); if (isInternal == false) { query.setFilter("internalOnly == false"); log.info("Only retrieving external friendly sources, not an internal user."); } results = (List<DataSource>) query.execute(); results = ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } log.info("Returning results: " + results.size()); return results; } @SuppressWarnings("unchecked") @Override public List<DataRequest> getProjectRequests(long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Data Requests for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(DataRequest.class); jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); List<DataRequest> results = null; try { List<DataRequest> returnedRequests = (List<DataRequest>) jdoQuery.execute(projectId); results = ServletUtils.makeGwtSafe(returnedRequests, pm); } finally { pm.close(); } return results; } @Override public long addDataRequest(DataRequest request) { ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Creating new Data Request for source: " + request.getDataSourceName()); request.setDataSourceName(request.getDataSourceName().trim()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(request); } finally { pm.close(); } return request.getRequestId(); } @Override public void updateDataRequest(DataRequest request) { if (request.getRequestId() == null) { throw new IllegalArgumentException( "Request has not been saved. Please call addDataRequest first."); } ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Updating DataRequest: " + request.getRequestId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(request); } finally { pm.close(); } } @Override public void removeDataRequest(DataRequest request) { if (request.getRequestId() == null) { log.info("Attempting to delete unsaved DataRequest. Ignoring."); return; } ServletUtils.requireAccess(userService.hasEditAccess(request.getParentProjectId())); log.info("Removing DataRequest: " + request.getRequestId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { DataRequest requestToDelete = pm.getObjectById(DataRequest.class, request.getRequestId()); pm.deletePersistent(requestToDelete); } finally { pm.close(); } } @Override public List<Filter> getFilters(long projectId) { return getFiltersByType(projectId, null); } @SuppressWarnings("unchecked") private List<Filter> getFiltersByType(long projectId, DatumType filterType) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting Filters for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(Filter.class); List<Filter> jdoResults; try { if (filterType == null) { jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoResults = (List<Filter>) jdoQuery.execute(projectId); } else { jdoQuery.declareParameters("Long parentProjectParam, DatumType filterTypeParam"); jdoQuery.setFilter( "parentProjectId == parentProjectParam && filterType == filterTypeParam"); jdoResults = (List<Filter>) jdoQuery.execute(projectId, filterType); } return ServletUtils.makeGwtSafe(jdoResults, pm); } finally { pm.close(); } } @Override public long addFilter(Filter filter) { ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Adding filter for project: " + filter.getParentProjectId()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(filter); } finally { pm.close(); } return filter.getId(); } @Override public void updateFilter(Filter filter) { if (filter.getId() == null) { throw new IllegalArgumentException( "Filter has not been saved. Please call addFilter first."); } ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Updating filter: " + filter.getId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { pm.makePersistent(filter); } finally { pm.close(); } } @Override public void removeFilter(Filter filter) { if (filter.getId() == null) { log.info("Attempting to delete unsaved Filter. Ignoring."); return; } ServletUtils.requireAccess(userService.hasEditAccess(filter.getParentProjectId())); log.info("Deleting filter: " + filter.getId().toString()); PersistenceManager pm = pmf.getPersistenceManager(); try { Filter filterToDelete = pm.getObjectById(Filter.class, filter.getId()); pm.deletePersistent(filterToDelete); } finally { pm.close(); } } @SuppressWarnings("unchecked") @Override public List<Bug> getProjectBugsById(long projectId) { return getProjectData(Bug.class, projectId); } @SuppressWarnings("unchecked") @Override public void updateBugAssociations(long bugId, long attributeId, long componentId, long capabilityId) { updateAssociations(Bug.class, bugId, attributeId, componentId, capabilityId); } /** * Try to upload a new bug into the GAE datastore. If a bug with the same Bug ID already exists, * it will be updated. This is a friendly function; it will not throw if there's an error * adding the bug. */ @Override public void addBug(Bug bug) { addBug(bug, userService.getEmail()); } @SuppressWarnings("unchecked") @Override public void addBug(Bug bug, String asEmail) { log.info("Trying to add Bug: " + bug.getTitle() + " for project " + bug.getParentProjectId()); ServletUtils.requireAccess(userService.hasEditAccess(bug.getParentProjectId(), asEmail)); // Trim long fields. bug.setTitle(StringUtil.trimString(bug.getTitle())); saveOrUpdateDatum(bug); } @SuppressWarnings("unchecked") @Override public List<Checkin> getProjectCheckinsById(long projectId) { return getProjectData(Checkin.class, projectId); } @Override public void addCheckin(Checkin checkin) { addCheckin(checkin, userService.getEmail()); } /** * Try to upload a new Checkin into the GAE datastore. If a Checkin with the same Checkin ID * already exists, it will be updated. */ @SuppressWarnings("unchecked") @Override public void addCheckin(Checkin checkin, String asEmail) { log.info("Trying to add Checkin: " + checkin.getSummary()); ServletUtils.requireAccess(userService.hasEditAccess(checkin.getParentProjectId(), asEmail)); checkin.setSummary(StringUtil.trimString(checkin.getSummary())); saveOrUpdateDatum(checkin); } @SuppressWarnings("unchecked") @Override public void updateCheckinAssociations(long checkinId, long attributeId, long componentId, long capabilityId) { updateAssociations(Checkin.class, checkinId, attributeId, componentId, capabilityId); } @SuppressWarnings("unchecked") @Override public List<TestCase> getProjectTestCasesById(long projectId) { return getProjectData(TestCase.class, projectId); } @SuppressWarnings("unchecked") @Override public void updateTestAssociations(long testCaseId, long attributeId, long componentId, long capabilityId) { updateAssociations(TestCase.class, testCaseId, attributeId, componentId, capabilityId); } @Override public void addTestCase(TestCase test) { addTestCase(test, userService.getEmail()); } /** * Try to upload a new bug into the GAE datastore. If a test case with the same ID already * exists, it will be updated. */ @SuppressWarnings("unchecked") @Override public void addTestCase(TestCase test, String asEmail) { log.info("Trying to add Test: " + test.getTitle()); ServletUtils.requireAccess(userService.hasEditAccess(test.getParentProjectId(), asEmail)); // Trim long fields. test.setTitle(StringUtil.trimString(test.getTitle())); saveOrUpdateDatum(test); } @SuppressWarnings("unchecked") private <T extends UploadedDatum> List<T> getProjectData(Class<T> clazz, long projectId) { ServletUtils.requireAccess(userService.hasViewAccess(projectId)); log.info("Getting data for project: " + Long.toString(projectId)); PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(clazz); jdoQuery.declareParameters("Long parentProjectParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam"); jdoQuery.setOrdering("externalId asc"); List<T> projectData = null; try { List<T> results = (List<T>) jdoQuery.execute(projectId); projectData = ServletUtils.makeGwtSafe(results, pm); } finally { pm.close(); } return projectData; } /** * Saves a new datum, or updates an existing datum in the database if it already exists. * * @param datum */ @SuppressWarnings("unchecked") private <T extends UploadedDatum> void saveOrUpdateDatum(T datum) { PersistenceManager pm = pmf.getPersistenceManager(); Query jdoQuery = pm.newQuery(datum.getClass()); jdoQuery.declareParameters("Long parentProjectParam, Long externalIdParam"); jdoQuery.setFilter("parentProjectId == parentProjectParam && externalId == externalIdParam"); try { // There are two ways an existing item may exist: the same primary key, or the same // parent project ID and bug ID. T oldDatum = null; if (datum.getInternalId() != null) { // If it's the same primary key, make sure it makes sense to overwrite it. The existing // bug should be non-null (we shouldn't have a pkey if it's unsaved already) and match // projects. oldDatum = (T) pm.getObjectById(datum.getClass(), datum.getInternalId()); ServletUtils.requireAccess(oldDatum != null); ServletUtils.requireAccess(oldDatum.getParentProjectId() == datum.getParentProjectId()); } else { // Try to load by a combination of project and external IDs. List<T> results = (List<T>) jdoQuery.execute(datum.getParentProjectId(), datum.getExternalId()); if (results.size() > 0) { oldDatum = results.get(0); } } if (oldDatum != null) { datum.setInternalId(oldDatum.getInternalId()); transferAssignments(oldDatum, datum); } else { applyFilters(datum); } pm.makePersistent(datum); } finally { pm.close(); } } private <T extends UploadedDatum> void updateAssociations(Class<T> clazz, long internalId, long attributeId, long componentId, long capabilityId) { PersistenceManager pm = pmf.getPersistenceManager(); try { T datum = pm.getObjectById(clazz, internalId); if (datum == null) { log.info("No results when querying for datum ID: " + internalId); return; } ServletUtils.requireAccess(userService.hasEditAccess(datum.getParentProjectId())); boolean updated = false; if (attributeId >= 0) { datum.setTargetAttributeId(attributeId == 0 ? null : attributeId); updated = true; } if (componentId >= 0) { datum.setTargetComponentId(componentId == 0 ? null : componentId); updated = true; } if (capabilityId >= 0) { datum.setTargetCapabilityId(capabilityId == 0 ? null : capabilityId); updated = true; } if (updated) { pm.makePersistent(datum); } } finally { pm.close(); } } /** * Iff the old datum (from the database) has an assigned attribute, component, or capability * AND the new datum doesn't have an assignment, we copy the old assignment over. * * @param oldDatum the old item. * @param newDatum the new item; it will have the a/c/c set from the old item. */ private void transferAssignments(UploadedDatum oldDatum, UploadedDatum newDatum) { if (positive(oldDatum.getTargetAttributeId()) && !positive(newDatum.getTargetAttributeId())) { newDatum.setTargetAttributeId(oldDatum.getTargetAttributeId()); } if (positive(oldDatum.getTargetComponentId()) && !positive(newDatum.getTargetComponentId())) { newDatum.setTargetComponentId(oldDatum.getTargetComponentId()); } if (positive(oldDatum.getTargetCapabilityId()) && !positive(newDatum.getTargetCapabilityId())) { newDatum.setTargetCapabilityId(oldDatum.getTargetCapabilityId()); } } private void applyFilters(UploadedDatum item) { // TODO(jimr): This is a poor way to filter items... it's a stop-gap solution until the recently // announced Full Text Search is available for the AppEngine datastore. List<Filter> filters = getFiltersByType(item.getParentProjectId(), item.getDatumType()); for (Filter filter : filters) { filter.apply(item); } } private boolean positive(Long value) { return value != null && value > 0; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service.impl; import com.google.appengine.api.users.User; import com.google.appengine.api.users.UserServiceFactory; import com.google.appengine.api.utils.SystemProperty; import com.google.appengine.api.utils.SystemProperty.Environment.Value; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.model.UserInfo; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * Implementation of UserService. Returns user and security information. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UserServiceImpl implements UserService { private static final String LOCAL_DOMAIN = System.getProperty("com.google.testing.testify.risk.frontend.localdomain"); private static final boolean WHITELISTING_ENABLED = Boolean.valueOf(System.getProperty("com.google.testing.testify.risk.frontend.whitelisting")); private static final Logger log = Logger.getLogger(UserServiceImpl.class.getName()); private final PersistenceManagerFactory pmf; private final com.google.appengine.api.users.UserService userService; @Inject public UserServiceImpl(PersistenceManagerFactory pmf) { this.pmf = pmf; // TODO(jimr): Inject this. this.userService = UserServiceFactory.getUserService(); } @Override public boolean isUserLoggedIn() { return getEmail() != null; } @Override public String getEmail() { User user = userService.getCurrentUser(); return user == null ? null : user.getEmail(); } @Override public boolean isWhitelistingEnabled() { return WHITELISTING_ENABLED; } @Override public boolean isWhitelisted() { if (isInternalUser()) { return true; } UserInfo user = getCurrentUserInfo(pmf.getPersistenceManager(), false); if (user == null) { return false; } return user.getIsWhitelisted(); } @Override public boolean isInternalUser() { if (isDevMode()) { return true; } String email = getEmail(); if (email == null || LOCAL_DOMAIN == null) { return false; } return email.endsWith(LOCAL_DOMAIN); } @Override public LoginStatus getLoginStatus(String returnUrl) { User user = userService.getCurrentUser(); String email = null; String url; if (user == null) { email = ""; url = userService.createLoginURL(returnUrl); } else { email = user.getEmail(); url = userService.createLogoutURL(returnUrl); } return new LoginStatus(user != null, url, email); } @Override public boolean hasAdministratorAccess() { return userService.isUserAdmin(); } @Override public boolean hasViewAccess(long projectId) { return hasAccess(ProjectAccess.VIEW_ACCESS, projectId); } @Override public boolean hasViewAccess(Project project) { return hasAccess(ProjectAccess.VIEW_ACCESS, project, getEmail()); } @Override public boolean hasEditAccess(long projectId) { return hasEditAccess(projectId, getEmail()); } @Override public boolean hasEditAccess(Project project) { return hasAccess(ProjectAccess.VIEW_ACCESS, project, getEmail()); } @Override public boolean hasEditAccess(long projectId, String asEmail) { return hasAccess(ProjectAccess.EDIT_ACCESS, projectId, asEmail); } @Override public boolean hasOwnerAccess(long projectId) { return hasAccess(ProjectAccess.OWNER_ACCESS, projectId); } @Override public boolean hasAccess(ProjectAccess accessLevel, long projectId) { return hasAccess(accessLevel, projectId, getEmail()); } @Override public boolean hasAccess(ProjectAccess accessLevel, long projectId, String asEmail) { return hasAccess(accessLevel, getProject(projectId), asEmail); } private boolean hasAccess(ProjectAccess accessLevel, Project project, String asEmail) { if (project == null) { log.warning("Call to hasAccess with a null project."); return false; } ProjectAccess accessHas = getAccessLevel(project, asEmail); log.info("Access has: " + accessHas.name() + " Access desired: " + accessLevel.name()); return accessHas.hasAccess(accessLevel); } @Override public ProjectAccess getAccessLevel(long projectId) { return getAccessLevel(getProject(projectId), getEmail()); } @Override public ProjectAccess getAccessLevel(Project project) { return getAccessLevel(project, getEmail()); } @Override public ProjectAccess getAccessLevel(long projectId, String asEmail) { return getAccessLevel(getProject(projectId), asEmail); } private ProjectAccess getAccessLevel(Project project, String asEmail) { if (project == null) { log.warning("Call to getAccessLevel with a null project."); return ProjectAccess.NO_ACCESS; } if (asEmail == null) { if (project.getIsPubliclyVisible()) { return ProjectAccess.VIEW_ACCESS; } else { return ProjectAccess.NO_ACCESS; } } else { if (hasAdministratorAccess()) { return ProjectAccess.ADMINISTRATOR_ACCESS; } else if (project.getProjectOwners().contains(asEmail)) { return ProjectAccess.OWNER_ACCESS; } else if (project.getProjectEditors().contains(asEmail)) { return ProjectAccess.EDIT_ACCESS; } else if (project.getProjectViewers().contains(asEmail)) { return ProjectAccess.EXPLICIT_VIEW_ACCESS; } else if (project.getIsPubliclyVisible()) { return ProjectAccess.VIEW_ACCESS; } else { return ProjectAccess.NO_ACCESS; } } } @Override public List<Long> getStarredProjects() { log.info("Getting starred projects for current user."); PersistenceManager pm = pmf.getPersistenceManager(); List<Long> starredProjects = Lists.newArrayList(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); // Copy list items over since we cannot return the server-side list type to client-side code. if (userInfo != null) { for (long projectId : userInfo.getStarredProjects()) { starredProjects.add(projectId); } } } finally { pm.close(); } return starredProjects; } @Override public void starProject(long projectId) { log.info("Starring project: " + projectId); PersistenceManager pm = pmf.getPersistenceManager(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); if (userInfo != null) { userInfo.starProject(projectId); pm.makePersistent(userInfo); } } finally { pm.close(); } } @Override public void unstarProject(long projectId) { log.info("Unstarring project: " + projectId); PersistenceManager pm = pmf.getPersistenceManager(); try { UserInfo userInfo = getCurrentUserInfo(pm, true); if (userInfo != null) { userInfo.unstarProject(projectId); pm.makePersistent(userInfo); } } finally { pm.close(); } } @Override public boolean isDevMode() { Value env = SystemProperty.environment.value(); log.info("System environment: " + env.toString()); return env.equals(SystemProperty.Environment.Value.Development); } /** * Returns all information Testify knows about the currently logged in user. If the logged in user * is not currently in Testify, a new UserInfo entry will be created. Also, will return null if * the user is not currently logged in. * * @param pm The PersistenceManager session for which the UserInfo object was returned. */ private UserInfo getCurrentUserInfo(PersistenceManager pm, boolean createIfMissing) { User appEngineUser = userService.getCurrentUser(); if (appEngineUser == null) { log.info("Unable to get user info. User is not logged in."); return null; } // If they are logged in, get the Testify UserInfo record on file. If unavailable, create a new // entry. String loggedInUserId = appEngineUser.getUserId(); String currentEmail = appEngineUser.getEmail(); Query jdoQuery = pm.newQuery(UserInfo.class); jdoQuery.declareParameters("String userIdParam"); jdoQuery.setFilter("userId == userIdParam"); log.info("Querying for user " + currentEmail + " by id " + loggedInUserId); UserInfo user = queryAndReturnFirst(jdoQuery, loggedInUserId); if (user != null) { // Update email address if missing or different. if (!currentEmail.equals(user.getCurrentEmail())) { log.info("Adding or updating email for " + currentEmail + " id " + loggedInUserId); user.setCurrentEmail(currentEmail); pm.makePersistent(user); } } else { // Try to find by email instead. log.info("Querying for user " + currentEmail + " by email instead."); jdoQuery = pm.newQuery(UserInfo.class); jdoQuery.declareParameters("String currentEmailParam"); jdoQuery.setFilter("currentEmail == currentEmailParam"); user = queryAndReturnFirst(jdoQuery, currentEmail); if (user != null) { // Add the user's user ID since we now know it. if (user.getUserId() == null || user.getUserId().equals("")) { log.info("Adding user ID for " + currentEmail + "."); user.setUserId(appEngineUser.getUserId()); pm.makePersistent(user); } else { log.severe("Found a user by email but user ID was set to a different ID."); user = null; } } } if (user == null) { log.info("Tried to get info for " + loggedInUserId + " but no entry was found."); if (createIfMissing) { log.info("Creating new UserInfo for user: " + loggedInUserId); user = new UserInfo(); user.setUserId(loggedInUserId); user.setCurrentEmail(currentEmail); pm.makePersistent(user); } } return user; } @SuppressWarnings("unchecked") private UserInfo queryAndReturnFirst(Query query, String param) { List<UserInfo> users = (List<UserInfo>) query.execute(param); if (users.size() > 0) { return users.get(0); } return null; } /** * Loads a project. This isn't done using ProjectServiceImpl because it would create a circular * dependency. * * @param id projectId to load. * @return the loaded project. */ private Project getProject(long id) { // TODO(jimr): To reduce this code duplication, project loading should be done at a lower level // so that object can be injected both here and into project service. log.info("Getting project: " + Long.toString(id)); PersistenceManager pm = pmf.getPersistenceManager(); try { return pm.getObjectById(Project.class, id); } finally { pm.close(); } } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.service; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.util.List; /** * Server service for accessing user details or permissions. * * @author jimr@google.com (Jim Reardon) */ public interface UserService { public boolean isUserLoggedIn(); public boolean isInternalUser(); public String getEmail(); public LoginStatus getLoginStatus(String returnUrl); public boolean isWhitelistingEnabled(); public boolean isWhitelisted(); public boolean isDevMode(); public ProjectAccess getAccessLevel(long projectId); public ProjectAccess getAccessLevel(Project project); public ProjectAccess getAccessLevel(long projectId, String asEmail); public boolean hasAdministratorAccess(); public boolean hasViewAccess(long projectId); public boolean hasViewAccess(Project project); public boolean hasEditAccess(long projectId); public boolean hasEditAccess(Project project); public boolean hasEditAccess(long projectId, String asEmail); public boolean hasOwnerAccess(long projectId); public boolean hasAccess(ProjectAccess accessLevel, long project); public boolean hasAccess(ProjectAccess accessLevel, long project, String asEmail); public List<Long> getStarredProjects(); public void starProject(long projectId); public void unstarProject(long projectId); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; /** * Exception thrown when trying to access project information for which the current user does not * have sufficient permission. * * @author chrsmith@google.com (Chris Smith) */ public class InsufficientPrivlegesException extends RuntimeException { private final String message; public InsufficientPrivlegesException(String message) { this.message = message; } @Override public String getMessage() { return "Error: You do not have sufficient privleges. " + message; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.LoginStatus; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc; import java.util.List; /** * Service allowing access to user / login data. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UserRpcImpl extends RemoteServiceServlet implements UserRpc { private final UserService userService; @Inject public UserRpcImpl(UserService userService) { this.userService = userService; } @Override public ProjectAccess getAccessLevel(long projectId) { return userService.getAccessLevel(projectId); } @Override public LoginStatus getLoginStatus(String returnUrl) { return userService.getLoginStatus(returnUrl); } @Override public List<Long> getStarredProjects() { return userService.getStarredProjects(); } @Override public boolean hasAdministratorAccess() { return userService.hasAdministratorAccess(); } @Override public boolean hasEditAccess(long projectId) { return userService.hasEditAccess(projectId); } @Override public boolean isDevMode() { return userService.isDevMode(); } @Override public void starProject(long projectId) { userService.starProject(projectId); } @Override public void unstarProject(long projectId) { userService.unstarProject(projectId); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccLabel; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpc; import java.util.List; /** * RPC methods that allow interaction with project data. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class ProjectRpcImpl extends RemoteServiceServlet implements ProjectRpc { private final ProjectService projectService; @Inject public ProjectRpcImpl(ProjectService projectService) { this.projectService = projectService; } @Override public Long createAttribute(Attribute attribute) { return projectService.createAttribute(attribute); } @Override public Capability createCapability(Capability capability) { return projectService.createCapability(capability); } @Override public Long createComponent(Component component) { return projectService.createComponent(component); } @Override public Long createProject(Project project) { return projectService.createProject(project); } @Override public Capability getCapabilityById(long projectId, long capabilityId) { return projectService.getCapabilityById(projectId, capabilityId); } @Override public List<AccLabel> getLabels(long projectId) { return projectService.getLabels(projectId); } @Override public List<Attribute> getProjectAttributes(long projectId) { return projectService.getProjectAttributes(projectId); } @Override public Project getProjectById(long projectId) { return projectService.getProjectById(projectId); } @Override public List<Capability> getProjectCapabilities(long projectId) { return projectService.getProjectCapabilities(projectId); } @Override public List<Component> getProjectComponents(long projectId) { return projectService.getProjectComponents(projectId); } @Override public List<Project> query(String query) { return projectService.query(query); } @Override public List<Project> queryUserProjects() { return projectService.queryUserProjects(); } @Override public void removeAttribute(Attribute attribute) { projectService.removeAttribute(attribute); } @Override public void removeCapability(Capability capability) { projectService.removeCapability(capability); } @Override public void removeComponent(Component component) { projectService.removeComponent(component); } @Override public void removeProject(Project project) { projectService.removeProject(project); } @Override public void reorderAttributes(long projectId, List<Long> newOrder) { projectService.reorderAttributes(projectId, newOrder); } @Override public void reorderCapabilities(long projectId, List<Long> newOrder) { projectService.reorderCapabilities(projectId, newOrder); } @Override public void reorderComponents(long projectId, List<Long> newOrder) { projectService.reorderComponents(projectId, newOrder); } @Override public Attribute updateAttribute(Attribute attribute) { return projectService.updateAttribute(attribute); } @Override public void updateCapability(Capability capability) { projectService.updateCapability(capability); } @Override public Component updateComponent(Component component) { return projectService.updateComponent(component); } @Override public void updateProject(Project project) { projectService.updateProject(project); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.common.collect.Lists; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.Attribute; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Capability; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.Component; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.FailureRate; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.model.UserImpact; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import com.google.testing.testify.risk.frontend.shared.rpc.TestProjectCreatorRpc; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; import javax.jdo.Query; /** * A simple servlet that allows an admin to create a test project populated with some data. * Useful for testing purposes and to make sure everything is working how it should. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class TestProjectCreatorRpcImpl extends RemoteServiceServlet implements TestProjectCreatorRpc { private static final Logger LOG = Logger.getLogger(TestProjectCreatorRpcImpl.class.getName()); private final ProjectService projectService; private final UserService userService; private final DataService dataService; private final PersistenceManagerFactory pmf; @Inject public TestProjectCreatorRpcImpl(ProjectService projectService, UserService userService, DataService dataService, PersistenceManagerFactory pmf) { this.projectService = projectService; this.userService = userService; this.dataService = dataService; this.pmf = pmf; } @SuppressWarnings("unchecked") @Override public void createStandardDataSources() { LOG.info("Injecting standard datasources."); boolean admin = userService.hasAdministratorAccess(); boolean devMode = userService.isDevMode(); ServletUtils.requireAccess(admin || devMode); DataSource bugSource = new DataSource(); bugSource.setInternalOnly(true); bugSource.setName("Bug Database"); bugSource.setParameters(Lists.newArrayList("Path", "Hotlist")); DataSource testManager = new DataSource(); testManager.setInternalOnly(true); testManager.setName("Test Database"); testManager.setParameters(Lists.newArrayList("Label", "ProjectID", "SavedSearchID")); DataSource perforce = new DataSource(); perforce.setInternalOnly(true); perforce.setName("Perforce"); perforce.setParameters(Lists.newArrayList("Path")); DataSource issueTracker = new DataSource(); issueTracker.setInternalOnly(false); issueTracker.setName("Issue Tracker"); issueTracker.setParameters(Lists.newArrayList("Project", "Label", "Owner")); DataSource other = new DataSource(); other.setInternalOnly(false); other.setName("Other..."); other.setParameters(new ArrayList<String>()); List<DataSource> all = Lists.newArrayList( bugSource, testManager, perforce, issueTracker, other); PersistenceManager pm = pmf.getPersistenceManager(); try { // Remove any data source from what we will persist if it already exists. DataSource source; Iterator<DataSource> i = all.iterator(); while (i.hasNext()) { source = i.next(); Query query = pm.newQuery(DataSource.class); query.declareParameters("String nameParam"); query.setFilter("name == nameParam"); if (((List<DataSource>) query.execute(source.getName())).size() > 0) { i.remove(); } } pm.makePersistentAll(all); } finally { pm.close(); } } @Override public Project createTestProject() { LOG.info("Starting to create a sample project..."); boolean admin = userService.hasAdministratorAccess(); boolean devMode = userService.isDevMode(); ServletUtils.requireAccess(admin || devMode); // Project. LOG.info("Creating project."); Project project = new Project(); String testDescription = "An example project created by TestProjectCreator."; project.setDescription(testDescription); project.setName("Test Project " + System.currentTimeMillis()); Long projectId = projectService.createProject(project); // Attributes. LOG.info("Creating attributes."); List<Attribute> attributes = Lists.newArrayList(); Attribute attr1 = new Attribute(); attr1.setParentProjectId(projectId); attr1.setName("Fast"); attr1.setDescription("This should be speedy."); attr1.addLabel("owner: alaska@example"); attr1.addLabel("pm: will@example"); attr1.setAttributeId(projectService.createAttribute(attr1)); attributes.add(attr1); Attribute attr2 = new Attribute(); attr2.setParentProjectId(projectId); attr2.setName("Simple"); attr2.addLabel("owner: alaska@example"); attr2.setAttributeId(projectService.createAttribute(attr2)); attributes.add(attr2); Attribute attr3 = new Attribute(); attr3.setParentProjectId(projectId); attr3.setName("Secure"); attr3.addLabel("owner: margo@example"); attr3.addLabel("tester: quentin@example"); attr3.setAttributeId(projectService.createAttribute(attr3)); attributes.add(attr3); // Components. LOG.info("Creating components."); ArrayList<Component> components = Lists.newArrayList(); Component comp1 = new Component(projectId); comp1.setName("Shopping Cart"); comp1.addLabel("dev lead: miles@example"); comp1.addLabel("tester: katherine@example"); comp1.setDescription("Contains items people want to buy."); comp1.setComponentId(projectService.createComponent(comp1)); components.add(comp1); Component comp2 = new Component(projectId); comp2.setName("Sales Channel"); comp2.addLabel("dev lead: colin@example"); comp2.setComponentId(projectService.createComponent(comp2)); components.add(comp2); Component comp3 = new Component(projectId); comp3.setName("Social"); comp3.addLabel("owner: alaska@example"); comp3.setComponentId(projectService.createComponent(comp3)); components.add(comp3); Component comp4 = new Component(projectId); comp4.setName("Search"); comp4.setComponentId(projectService.createComponent(comp4)); components.add(comp4); // Capabilities. LOG.info("Creating capabilities."); ArrayList<Capability> capabilities = Lists.newArrayList(); Capability capa1 = new Capability( projectId, attributes.get(0).getAttributeId(), components.get(1).getComponentId()); capa1.setName("Credit card processing takes less than 5 seconds"); capa1.setFailureRate(FailureRate.OFTEN); capa1.addLabel("external"); capa1.addLabel("load test"); capa1.setDescription("Order is completed from clicking 'ORDER NOW' to success page."); capa1.setUserImpact(UserImpact.MINIMAL); capa1.setCapabilityId(projectService.createCapability(capa1).getCapabilityId()); capabilities.add(capa1); Capability capa2 = new Capability( projectId, attributes.get(0).getAttributeId(), components.get(1).getComponentId()); capa2.setName("Saved addresses and credit cards appear quickly"); capa2.setFailureRate(FailureRate.OCCASIONALLY); capa2.setUserImpact(UserImpact.MAXIMAL); capa2.setCapabilityId(projectService.createCapability(capa2).getCapabilityId()); capabilities.add(capa2); Capability capa3 = new Capability( projectId, attributes.get(2).getAttributeId(), components.get(1).getComponentId()); capa3.setName("All traffic is sent over https"); capa3.addLabel("ssl"); capa3.setFailureRate(FailureRate.NA); capa3.setUserImpact(UserImpact.MAXIMAL); capa3.setCapabilityId(projectService.createCapability(capa3).getCapabilityId()); capabilities.add(capa3); Capability capa4 = new Capability( projectId, attributes.get(2).getAttributeId(), components.get(3).getComponentId()); capa4.setName("Items removed from inventory do not appear in search"); capa4.setFailureRate(FailureRate.VERY_RARELY); capa4.setUserImpact(UserImpact.NA); capa4.setCapabilityId(projectService.createCapability(capa4).getCapabilityId()); capabilities.add(capa4); // Bugs. LOG.info("Creating bugs."); List<Bug> bugs = Lists.newArrayList(); Bug bug1 = new Bug(); bug1.setExternalId(42L); bug1.setTitle("SSL certificate error in some browsers."); bug1.addBugGroup("security"); bug1.addBugGroup("checkout"); bug1.setParentProjectId(projectId); bug1.setPriority(1L); bug1.setSeverity(2L); bug1.setState("Open"); bug1.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug1.setStateDate(System.currentTimeMillis() - (84000000 * 4)); bug1.setBugUrl("http://example/42"); dataService.addBug(bug1); bugs.add(bug1); Bug bug2 = new Bug(); bug2.setExternalId(123L); bug2.setTitle("+1 button is not showing on products with prime number IDs."); bug2.addBugGroup("social"); bug2.addBugGroup("browsing"); bug2.setParentProjectId(projectId); bug2.setPriority(1L); bug2.setSeverity(2L); bug2.setState("Open"); bug2.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug2.setStateDate(System.currentTimeMillis() - (84000000 * 2)); bug2.setBugUrl("http://example/123"); dataService.addBug(bug2); bugs.add(bug2); Bug bug3 = new Bug(); bug3.setExternalId(122L); bug3.setTitle("Search results always return developer's favorite item"); bug3.addBugGroup("search"); bug3.addBugGroup("accuracy"); bug3.setParentProjectId(projectId); bug3.setPriority(4L); bug3.setSeverity(4L); bug3.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); bug3.setState("Closed"); bug3.setStateDate(System.currentTimeMillis() - (84000000 * 10)); bug3.setBugUrl("http://example/34121"); dataService.addBug(bug3); bugs.add(bug3); // Checkins. LOG.info("Creating checkins."); Checkin checkin1 = new Checkin(); checkin1.setChangeUrl("http://example/code/16358580"); checkin1.setExternalId(16358580L); checkin1.addDirectoryTouched("java/com/example/DoorKnobFactoryFactory"); checkin1.setParentProjectId(projectId); checkin1.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); checkin1.setStateDate(System.currentTimeMillis() - (84000000 * 2)); checkin1.setSummary("Add factory to create a factory to provide Door Knob objects."); dataService.addCheckin(checkin1); Checkin checkin2 = new Checkin(); checkin2.setChangeUrl("http://example/code/16358581"); checkin2.setExternalId(16358581L); checkin2.addDirectoryTouched("java/com/example/Search"); checkin2.setParentProjectId(projectId); checkin2.setStateDate(System.currentTimeMillis() - (84000000 * 7)); checkin2.setSummary("Search engine optimizations"); dataService.addCheckin(checkin2); // Tests. LOG.info("Creating tests."); TestCase testcase1 = new TestCase(); testcase1.setParentProjectId(projectId); testcase1.setExternalId(1042L); testcase1.setTestCaseUrl("http://example/test/1042"); testcase1.setTitle("Search for 'dogfood'"); testcase1.setTargetAttributeId(attributes.get(1).getAttributeId()); testcase1.setTargetComponentId(components.get(1).getComponentId()); dataService.addTestCase(testcase1); TestCase testcase2 = new TestCase(); testcase2.setParentProjectId(projectId); testcase2.setExternalId(1043L); testcase2.setTestCaseUrl("http://example/test/1043"); testcase2.setTitle("Post an item to your favorite social network via sharing functions"); testcase2.setTargetCapabilityId(capabilities.get(3).getCapabilityId()); dataService.addTestCase(testcase2); for (int i = 0; i < 6; i++) { TestCase testcase3 = new TestCase(); testcase3.setParentProjectId(projectId); testcase3.setExternalId(Long.valueOf(1044 + i * 100)); testcase3.setTestCaseUrl("http://example/test/" + i); testcase3.setTitle("Some Random Automated Test " + i); testcase3.setState("Passed"); testcase3.setStateDate(System.currentTimeMillis() - (84000000L * i)); testcase3.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase3); } for (int i = 0; i < 4; i++) { TestCase testcase4 = new TestCase(); testcase4.setParentProjectId(projectId); testcase4.setExternalId(Long.valueOf(1045 + i * 100)); testcase4.setTestCaseUrl("http://example/test/" + i); testcase4.setTitle("Some Random Manual Test " + i); testcase4.setState("Failed"); testcase4.setStateDate(System.currentTimeMillis() - (84000000L * i)); testcase4.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase4); } for (int i = 0; i < 2; i++) { TestCase testcase5 = new TestCase(); testcase5.setParentProjectId(projectId); testcase5.setExternalId(Long.valueOf(1046 + i * 100)); testcase5.setTestCaseUrl("http://example/test/" + i); testcase5.setTitle("Test We Never Run " + i); testcase5.setTargetCapabilityId(capabilities.get(0).getCapabilityId()); dataService.addTestCase(testcase5); } LOG.info("Done. Returning created project."); return project; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.rpc.impl; import com.google.gwt.user.server.rpc.RemoteServiceServlet; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.AccElementType; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataSource; import com.google.testing.testify.risk.frontend.model.Filter; import com.google.testing.testify.risk.frontend.model.Signoff; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.shared.rpc.DataRpc; import java.util.List; /** * RPC by which data details are retrieved or updated. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class DataRpcImpl extends RemoteServiceServlet implements DataRpc { private final DataService dataService; @Inject public DataRpcImpl(DataService dataService) { this.dataService = dataService; } @Override public void addBug(Bug bug) { dataService.addBug(bug); } @Override public void addCheckin(Checkin checkin) { dataService.addCheckin(checkin); } @Override public long addDataRequest(DataRequest request) { return dataService.addDataRequest(request); } @Override public long addFilter(Filter filter) { return dataService.addFilter(filter); } @Override public void addTestCase(TestCase testCase) { dataService.addTestCase(testCase); } @Override public List<DataSource> getDataSources() { return dataService.getDataSources(); } @Override public List<Filter> getFilters(long projectId) { return dataService.getFilters(projectId); } @Override public List<Bug> getProjectBugsById(long projectId) { return dataService.getProjectBugsById(projectId); } @Override public List<Checkin> getProjectCheckinsById(long projectId) { return dataService.getProjectCheckinsById(projectId); } @Override public List<DataRequest> getProjectRequests(long projectId) { return dataService.getProjectRequests(projectId); } @Override public List<TestCase> getProjectTestCasesById(long projectId) { return dataService.getProjectTestCasesById(projectId); } @Override public List<Signoff> getSignoffsByType(Long projectId, AccElementType type) { return dataService.getSignoffsByType(projectId, type); } @Override public Boolean isSignedOff(AccElementType type, Long elementId) { return dataService.isSignedOff(type, elementId); } @Override public void removeDataRequest(DataRequest request) { dataService.removeDataRequest(request); } @Override public void removeFilter(Filter filter) { dataService.removeFilter(filter); } @Override public void setSignedOff( Long projectId, AccElementType type, Long elementId, boolean isSignedOff) { dataService.setSignedOff(projectId, type, elementId, isSignedOff); } @Override public void updateBugAssociations( long bugId, long attributeId, long componentId, long capabilityId) { dataService.updateBugAssociations(bugId, attributeId, componentId, capabilityId); } @Override public void updateCheckinAssociations( long bugId, long attributeId, long componentId, long capabilityId) { dataService.updateCheckinAssociations(bugId, attributeId, componentId, capabilityId); } @Override public void updateDataRequest(DataRequest request) { dataService.updateDataRequest(request); } @Override public void updateFilter(Filter filter) { dataService.updateFilter(filter); } @Override public void updateTestAssociations( long testCaseId, long attributeId, long componentId, long capabilityId) { dataService.updateTestAssociations(testCaseId, attributeId, componentId, capabilityId); } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server; import com.google.inject.AbstractModule; import com.google.inject.Inject; import com.google.inject.Provides; import com.google.inject.Singleton; import com.google.inject.servlet.RequestScoped; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.service.impl.DataServiceImpl; import com.google.testing.testify.risk.frontend.server.service.impl.ProjectServiceImpl; import com.google.testing.testify.risk.frontend.server.service.impl.UserServiceImpl; import javax.jdo.JDOHelper; import javax.jdo.PersistenceManager; import javax.jdo.PersistenceManagerFactory; /** * Sets up injectable classes for Guice. Items listed here can be injected into the constructors * of servlets. * * @author jimr@google.com (Jim Reardon) */ public class GuiceProviderModule extends AbstractModule { @Provides @RequestScoped @Inject PersistenceManager getPersistenceManager(PersistenceManagerFactory pmf) { return pmf.getPersistenceManager(); } @Provides @Singleton PersistenceManagerFactory getPersistenceManagerFactory() { return JDOHelper.getPersistenceManagerFactory("transactions-optional"); } @Override protected void configure() { bind(DataService.class).to(DataServiceImpl.class); bind(ProjectService.class).to(ProjectServiceImpl.class); bind(UserService.class).to(UserServiceImpl.class); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.task; import com.google.common.collect.Sets; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.Bug; import com.google.testing.testify.risk.frontend.model.Checkin; import com.google.testing.testify.risk.frontend.model.TestCase; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This task processes a individual item to be uploaded (ie, one bug or one test) and inserts * it into the data store. * * The expected data are: * - json (the json of ONE data item: bug, test, checkin) * - user (the user to insert on behalf of) * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UploadDataTask extends HttpServlet { private static final Logger LOG = Logger.getLogger(UploadDataTask.class.getName()); public static final String QUEUE = "dataupload"; public static final String URL = "/_tasks/upload"; private final DataService dataService; @Inject public UploadDataTask(DataService dataService) { this.dataService = dataService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LOG.info("TestCaseUploadTask::GET called, returning unsupported exception."); error(resp, "<h1>GET is unsupported</h1>\nTo upload test cases, use POST."); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) { String user = req.getParameter("user"); String jsonString = req.getParameter("json"); try { // TODO(jimr): add impersonation of user in string user. JSONObject json = new JSONObject(jsonString); JSONObject item; if (json.has("bug")) { item = json.getJSONObject("bug"); Bug bug = new Bug(); bug.setParentProjectId(item.getLong("projectId")); bug.setExternalId(item.getLong("bugId")); bug.setTitle(item.getString("title")); bug.setPath(item.getString("path")); bug.setSeverity(item.getLong("severity")); bug.setPriority(item.getLong("priority")); bug.setBugGroups(Sets.newHashSet(StringUtil.csvToList(item.getString("groups")))); bug.setBugUrl(item.getString("url")); bug.setState(item.getString("status")); bug.setStateDate(item.getLong("statusDate")); dataService.addBug(bug); } else if (json.has("test")) { item = json.getJSONObject("test"); TestCase test = new TestCase(); test.setParentProjectId(item.getLong("projectId")); test.setExternalId(item.getLong("testId")); test.setTitle(item.getString("title")); test.setTags(Sets.newHashSet(StringUtil.csvToList(item.getString("tags")))); test.setTestCaseUrl(item.getString("url")); test.setState(item.getString("result")); test.setStateDate(item.getLong("resultDate")); dataService.addTestCase(test); } else if (json.has("checkin")) { item = json.getJSONObject("checkin"); Checkin checkin = new Checkin(); checkin.setParentProjectId(item.getLong("projectId")); checkin.setExternalId(item.getLong("checkinId")); checkin.setSummary(item.getString("summary")); checkin.setDirectoriesTouched( Sets.newHashSet(StringUtil.csvToList(item.getString("directories")))); checkin.setChangeUrl(item.getString("url")); checkin.setState(item.getString("state")); checkin.setStateDate(item.getLong("stateDate")); dataService.addCheckin(checkin); } else { LOG.severe("No applicable data found for json: " + json.toString()); } } catch (JSONException e) { // We don't issue a 500 or similar response code here to prevent retries, which would have // no different a result. LOG.severe("Couldn't parse input JSON: " + jsonString); return; } } private void error(HttpServletResponse resp, String errorText) throws IOException { resp.getOutputStream().print(errorText); resp.sendError(500); return; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.filter; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.server.service.UserService; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * Filters access to the application based off the whitelist field in a UserInfo object. * * @author jimr@google.com (Jim Reardon) */ @Singleton public class WhitelistFilter implements Filter { private static final Logger log = Logger.getLogger(WhitelistFilter.class.getName()); private final UserService userService; @Inject public WhitelistFilter(UserService userService) { this.userService = userService; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) response; if (userService.isWhitelistingEnabled() && !userService.isWhitelisted()) { String email = userService.getEmail(); if (email == null) { email = "(null)"; } log.warning("User not whitelisted tried to access server: " + email); httpResponse.getWriter().write("404 Not Found"); httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND); return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig arg0) { } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.api.impl; import com.google.common.collect.Lists; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.Project; import com.google.testing.testify.risk.frontend.server.service.DataService; import com.google.testing.testify.risk.frontend.server.service.ProjectService; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.util.DataRequestDocumentGenerator; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet for exposing project data requests to third party tools, so that those requests may be * fulfilled. * * @author chrsmith@google.com (Chris Smith) */ @Singleton public class DataApiImpl extends HttpServlet { private static final Logger log = Logger.getLogger(DataApiImpl.class.getName()); private final DataService dataService; private final ProjectService projectService; private final UserService userService; @Inject public DataApiImpl(DataService dataService, ProjectService projectService, UserService userService) { this.dataService = dataService; this.projectService = projectService; this.userService = userService; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("DataRequestServlet::GET"); if (!userService.isUserLoggedIn()) { resp.getWriter().print("You must be logged in to access this service."); resp.sendError(5000); return; } // Query all projects the current user (typically a role account) has EDIT access to. List<Project> projectsUserCanEdit = projectService.queryProjectsUserHasEditAccessTo(); // Query all data requests for those projects. List<DataRequest> relevantDataRequests = Lists.newArrayList(); for (Project project : projectsUserCanEdit) { relevantDataRequests.addAll(dataService.getProjectRequests(project.getProjectId())); } // Generate the XML document and serve. String xmlDocumentText = DataRequestDocumentGenerator.generateDocument(relevantDataRequests); resp.getWriter().write(xmlDocumentText); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { log.info("DataRequestServlet::POST"); resp.getWriter().write("Please call this URL using GET."); } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.api.impl; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TaskOptions.Method; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.testing.testify.risk.frontend.server.service.UserService; import com.google.testing.testify.risk.frontend.server.task.UploadDataTask; import com.google.testing.testify.risk.frontend.server.util.ServletUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This servlet accepts user data (JSON encoded) and passes it off to a task which does the actual * processing. {@link UploadDataTask} * * @author jimr@google.com (Jim Reardon) */ @Singleton public class UploadApiImpl extends HttpServlet { private static final Logger LOG = Logger.getLogger(UploadApiImpl.class.getName()); private final UserService userService; @Inject public UploadApiImpl(UserService userService) { this.userService = userService; } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { LOG.info("UploadDataServlet::GET called, returning unsupported exception."); error(resp, "<h1>GET is unsupported</h1>\nTo upload data, use POST."); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { BufferedReader reader = req.getReader(); StringBuilder input = new StringBuilder(); while (reader.ready()) { input.append(req.getReader().readLine()); } LOG.info("Input received: " + input.toString()); JSONArray json; try { json = new JSONArray(input.toString()); } catch (JSONException e) { LOG.warning("Couldn't parse JSON: " + e.toString()); error(resp, "Malformed JSON could not be parsed: " + e.toString()); return; } LOG.info("JSON received: " + json.toString()); JSONObject o; TaskOptions task; String email = userService.getEmail(); for (int i = 0; i < json.length(); i++) { try { o = json.getJSONObject(i); task = TaskOptions.Builder.withUrl(UploadDataTask.URL).method(Method.POST) .param("json", o.toString()) .param("user", email); ServletUtils.queueWithRetries(UploadDataTask.QUEUE, task, "Processing data item upload"); } catch (JSONException e) { LOG.warning("Couldn't parse item " + i + " in JSON array: " + e.toString()); resp.getOutputStream().print("<p>Couldn't parse item " + i + "</p>\n"); } } } private void error(HttpServletResponse resp, String errorText) throws IOException { resp.getOutputStream().print(errorText); resp.sendError(500); return; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.util; import com.google.appengine.api.taskqueue.Queue; import com.google.appengine.api.taskqueue.QueueFactory; import com.google.appengine.api.taskqueue.TaskOptions; import com.google.appengine.api.taskqueue.TransientFailureException; import com.google.appengine.api.utils.SystemProperty; import com.google.testing.testify.risk.frontend.server.InsufficientPrivlegesException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.logging.Logger; import javax.jdo.PersistenceManager; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; /** * Utility methods for servlets. * * @author jimr@google.com (Jim Reardon) */ public class ServletUtils { private static final String URL = System.getProperty("com.google.testing.testify.risk.frontend.url"); private static final Logger LOG = Logger.getLogger(ServletUtils.class.getName()); private static final int QUEUE_RETRIES = 10; private ServletUtils() {} // COV_NF_LINE /** * Throws an access exception if user doesn't have access to do the operation. EG: * ServerletUtils.requireAccess(userService.hasAccess(...)). * * @param hasAccess */ public static void requireAccess(boolean hasAccess) { // TODO(jimr): It'd be nice if this was less clunky. Figure out a way to do that. if (!hasAccess) { throw new InsufficientPrivlegesException("You don't have access to perform that action."); } } /** * Lists returned from GAE's PersistanceManager are a private type which cannot be marshalled to * client-side GWT code. This method simply copies elements from whatever input List<T> into a * GWT-friendly detached ArrayList<T>. * * @param inputList the list to safenize. * @param pm the persistence manager. This is needed in order to create a detached copy. * @return a copied, serialization-safe list. */ public static <T> List<T> makeGwtSafe(List<T> inputList, PersistenceManager pm) { List<T> copiedList = new ArrayList<T>(inputList.size()); for (T item : inputList) { copiedList.add(pm.detachCopy(item)); } return copiedList; } /** * Lists returned from GAE's PersistanceManager are a private type which cannot be marshalled to * client-side GWT code. This method simply copies elements from whatever input <T> into a * GWT-friendly detached <T>. * * @param input the item to safenize. * @param pm the persistence manager. This is needed in order to create a detached copy. * @return a copied, serialization-safe item. */ public static <T> T makeGwtSafe(T input, PersistenceManager pm) { return pm.detachCopy(input); } public static boolean queueWithRetries(String queueName, TaskOptions task, String description) { Queue queue = QueueFactory.getQueue(queueName); for (int i = 0; i < QUEUE_RETRIES; i++) { try { queue.add(task); return true; } catch (TransientFailureException e) { LOG.warning("Retrying queue add for task due to queue failure: " + description); } } LOG.severe("Could not enqueue task after " + QUEUE_RETRIES + "retries: " + description); return false; } public static void notifyRemovedAccess(String from, List<String> emails, String accessType, String project, String projectId) { notifyAccessChanged(from, emails, accessType, project, projectId, false); } public static void notifyAddedAccess(String from, List<String> emails, String accessType, String project, String projectId) { notifyAccessChanged(from, emails, accessType, project, projectId, true); } private static void notifyAccessChanged(String from, List<String> emails, String accessType, String project, String projectId, boolean isAdded) { LOG.info("Trying to message users about change in " + accessType + " access."); if (emails.size() < 1) { LOG.warning("No emails specified to notify."); return; } try { String url = URL + "/#/" + projectId +"/project-settings"; String verb = isAdded ? "added" : "removed"; String change = "You have been " + verb + " as an " + accessType + " of Test Analytics Project: " + project; Session session = Session.getDefaultInstance(new Properties(), null); for (String email : emails) { Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from, "Test Analytics on behalf of " + from)); LOG.info("Sending email to " + email + "(" + change + ")"); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); msg.setSubject(change); msg.setText(change + "\n\nThis Test Analytics project's URL:\n\n" + url + "\n\nIf you believe this was a mistake, contact " + from + " who made the change."); if (SystemProperty.environment.value().equals( SystemProperty.Environment.Value.Production)) { Transport.send(msg); } else { LOG.info("Not actually sending email; not in production environment."); } } } catch (UnsupportedEncodingException e) { // COV_NF_START LOG.severe("Couldn't send email."); } catch (AddressException e) { LOG.severe("Couldn't send email."); } catch (MessagingException e) { LOG.severe("Couldn't send email."); } // COV_NF_END } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.server.util; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.testing.testify.risk.frontend.model.DataRequest; import com.google.testing.testify.risk.frontend.model.DataRequestOption; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.StringWriter; import java.util.Collection; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; /** * Generates an XML document for external data collectors. * * @author chrsmith@google.com (Chris Smith) */ public class DataRequestDocumentGenerator { private DataRequestDocumentGenerator() {} // COV_NF_LINE /** * Returns an XML document describing the data requests. */ public static String generateDocument(List<DataRequest> allDataRequests) { try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); Element documentRoot = document.createElement("TestAnalytics"); document.appendChild(documentRoot); // Group all requests by their parent project. Multimap<Long, DataRequest> requestsByProject = getRequestsByProject(allDataRequests); for (Long projectId : requestsByProject.keySet()) { Element projectElement = document.createElement("DataRequests"); projectElement.setAttribute("ProjectID", Long.toString(projectId)); documentRoot.appendChild(projectElement); // Group project requests by data source. Collection<DataRequest> projectRequests = requestsByProject.get(projectId); Multimap<String, DataRequest> requestsBySource = getRequestsByDataSource(projectRequests); for (String sourceName : requestsBySource.keySet()) { Element dataSourceElement = document.createElement("DataRequest"); dataSourceElement.setAttribute("Type", sourceName); projectElement.appendChild(dataSourceElement); // Write out the configuration parameter strings for the data source. for (DataRequest request : requestsBySource.get(sourceName)) { for (DataRequestOption option : request.getDataRequestOptions()) { Element dataSourceParameter = document.createElement("Parameter"); dataSourceParameter.setAttribute("Name", option.getName()); dataSourceParameter.appendChild(document.createTextNode(option.getValue())); dataSourceElement.appendChild(dataSourceParameter); } } } } // Now dump the document in memory to a string. Transformer transformer = TransformerFactory.newInstance().newTransformer(); DOMSource source = new DOMSource(document); StreamResult result = new javax.xml.transform.stream.StreamResult(new StringWriter()); transformer.transform(source, result); return result.getWriter().toString(); // COV_NF_START } catch (TransformerConfigurationException tce) { return "Error in transformer configuration."; } catch (TransformerException te) { return "Error transforming document."; } catch (ParserConfigurationException pce) { return "Error in parser configuration."; } // COV_NF_END } private static Multimap<Long, DataRequest> getRequestsByProject( Collection<DataRequest> requests) { Multimap<Long, DataRequest> requestsByProject = HashMultimap.create(); for (DataRequest request : requests) { requestsByProject.put(request.getParentProjectId(), request); } return requestsByProject; } private static Multimap<String, DataRequest> getRequestsByDataSource( Collection<DataRequest> requests) { Multimap<String, DataRequest> requestsBySource = HashMultimap.create(); for (DataRequest request : requests) { requestsBySource.put(request.getDataSourceName(), request); } return requestsBySource; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for a Label. Labels can be assigned to any part of an ACC model. * A label is stored as a two-state label (essentially, a name and value pair). This can * represent things like: * "Priority-P4" where P4 is the value to the name Priority. * * For labels where there is not a name/value structure, the label is simply stored as the name. * "Security", for example, would have an empty value and the entire label text in name. * * The entire label is not stored as one text field, but can be generated by this class using * the function getLabelText(). This function should be used instead of doing this manually. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class AccLabel implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private Long projectId; @Persistent private AccElementType elementType; @Persistent private Long elementId; @Persistent private String name; @Persistent private String value; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public AccElementType getElementType() { return elementType; } public void setElementType(AccElementType elementType) { this.elementType = elementType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } /** * Will attempt to split a label into its name / value pair, or set it all as name if it is not * a two-state label. */ public void setLabelText(String labelText) { if (labelText == null) { name = null; value = null; } else { String[] split = labelText.split("-", 2); if (split.length > 0) { name = split[0]; if (split.length > 1) { value = split[1]; } } } } /** * Returns a combined label with the name and value in one string. Eg: * name=Priority value=P4 would become "Priority-P4". * name=Security value=null would become "Security". * @return the combined label. */ public String getLabelText() { String labelText = name; if (value != null) { labelText += "-" + value; } return labelText; } public void setElementId(Long elementId) { this.elementId = elementId; } public Long getElementId() { return elementId; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a bug or defect in a piece of software. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class Bug implements Serializable, UploadedDatum { /** Unique identifier to store the bug in App Engine. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the bug belongs to. */ @Persistent private Long parentProjectId; /** * Bug ID provided by the data provider. Must be unique across all bugs associated with this * project. */ @Persistent private Long externalId; /** Bug severity. Sev 1 - severe, Sev 4 - ignorable.*/ @Persistent private Long severity; /** Bug priority. Pri 1 - fix now, Pri 4 - puntable. */ @Persistent private Long priority; /** Arbitrary title of the bug. */ @Persistent private String title; /** Component path, or similar, of the bug. */ @Persistent private String path; /** State, eg: Closed, Open, Active, etc **/ @Persistent private String state; /** Date this bug was originally reported **/ @Persistent private Long stateDate; /** Attribute this bug should be associated with (if any). */ @Persistent private Long targetAttributeId; /** Component this bug should be associated with (if any). */ @Persistent private Long targetComponentId; /** Capability this bug should be associated with (if any). */ @Persistent private Long targetCapabilityId; /** * Bug group is a meta string to identify groups of bugs, typically for linking them to specific * components. For example, if the bug database is organized by component then the bug * group should be its path in the database. */ @Persistent private Set<String> groups = new HashSet<String>(); /** URL to identify view more information about the bug. */ @Persistent private String bugUrl; @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setInternalId(Long internalId) { this.internalId = internalId; } /** * @return the bug's internal ID, which is unique across all projects. */ @Override public Long getInternalId() { return internalId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } /** * @return an arbitrary ID associated with the bug. (The bug ID in an external bug database.) */ @Override public Long getExternalId() { return externalId; } public void setSeverity(Long severity) { this.severity = severity; } public Long getSeverity() { return severity; } public void setPriority(Long priority) { this.priority = priority; } public Long getPriority() { return priority; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public void addBugGroup(String groupName) { groups.add(groupName); } public void removeBugGroup(String groupName) { groups.remove(groupName); } public void setBugGroups(Set<String> bugGroups) { this.groups = bugGroups; } public Set<String> getBugGroups() { return groups; } /** * @return the group names associated with this bug as a comma separated list. */ public String getGroupsAsCommaSeparatedList() { return StringUtil.listToCsv(groups); } public void setBugUrl(String bugUrl) { this.bugUrl = bugUrl; } public String getBugUrl() { return bugUrl; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { return title; } @Override public String getLinkUrl() { return bugUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append("This bug is attached to the following groups: "); text.append(this.getGroupsAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return targetAttributeId != null; } @Override public boolean isAttachedToComponent() { return targetComponentId != null; } @Override public boolean isAttachedToCapability() { return targetCapabilityId != null; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public DatumType getDatumType() { return DatumType.BUGS; } @Override public String getField(String field) { if ("Title".equals(field)) { return title; } else if ("Path".equals(field)) { return path; } else if ("Labels".equals(field)) { return getGroupsAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.util.Collection; /** * Represents an Attribute x Component intersection for calculating risk. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ public class CapabilityIntersectionData { private final Attribute parentAttribute; private final Component parentComponent; private final Collection<Capability> cellCapabilities; public CapabilityIntersectionData( Attribute parentAttribute, Component parentComponent, Collection<Capability> cellCapabilities) { this.parentAttribute = parentAttribute; this.parentComponent = parentComponent; this.cellCapabilities = cellCapabilities; } public Attribute getParentAttribute() { return parentAttribute; } public Component getParentComponent() { return parentComponent; } /** Project Capabilities associated with the Attribute x Component. */ public Collection<Capability> getCapabilities() { return cellCapabilities; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for storing Project data. * * @author chrsmith@google.com (Chris Smith) * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Project implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long projectId; @Persistent private String name; /** * Full paragraph or page-length description of the project. */ @Persistent private String description; /** * This field controls whether or not the project is listed in public queries. */ @Persistent private Boolean isPubliclyVisible = false; /** * Email addresses of users with owner access. They can do anything editors can do as well as * delete the project.. */ @Persistent private List<String> projectOwners = new ArrayList<String>(); /** * Email addresses of users with editor access. They can add, edit, or update project data. */ @Persistent private List<String> projectEditors = new ArrayList<String>(); /** * Email addresses of users with view access. They can view but not edit project data. */ @Persistent private List<String> projectViewers = new ArrayList<String>(); /** * Allows the server-side to set the permissions so UI code has easy access without executing * an RPC. Server-side code should never rely on this value. */ @NotPersistent private ProjectAccess cachedAccessLevel; /** * Returns the Project's ID. Note that this will return null in the case the project hasn't been * persisted in the backing store (and doesn't have an ID yet). */ public Long getProjectId() { return projectId; } public void setProjectId(long projectId) { this.projectId = projectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setIsPubliclyVisible(Boolean isPubliclyVisible) { this.isPubliclyVisible = isPubliclyVisible; } public boolean getIsPubliclyVisible() { return isPubliclyVisible; } public void addProjectOwner(String ownerEmailAddress) { if (!projectOwners.contains(ownerEmailAddress)) { projectOwners.add(ownerEmailAddress); } } public void removeProjectOwner(String ownerEmailAddress) { projectOwners.remove(ownerEmailAddress); } public void setProjectOwners(List<String> projectOwners) { this.projectOwners = projectOwners; } public List<String> getProjectOwners() { return projectOwners; } public void addProjectEditor(String editorEmailAddress) { if (!projectEditors.contains(editorEmailAddress)) { projectEditors.add(editorEmailAddress); } } public void removeProjectEditor(String editorEmailAddress) { projectEditors.remove(editorEmailAddress); } public void setProjectEditors(List<String> projectEditors) { this.projectEditors = projectEditors; } public List<String> getProjectEditors() { return projectEditors; } public void addProjectView(String viewEmailAddress) { if (!projectViewers.contains(viewEmailAddress)) { projectViewers.add(viewEmailAddress); } } public void removeProjectViewer(String viewerEmailAddress) { projectViewers.remove(viewerEmailAddress); } public void setProjectViewers(List<String> projectViewers) { this.projectViewers = projectViewers; } public List<String> getProjectViewers() { return projectViewers; } public void setCachedAccessLevel(ProjectAccess cachedAccessLevel) { this.cachedAccessLevel = cachedAccessLevel; } public ProjectAccess getCachedAccessLevel() { return cachedAccessLevel; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a code checkin. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class Checkin implements Serializable, UploadedDatum { /** Unique identifier to store the checkin in App Engine. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the checkin belongs to. */ @Persistent private Long parentProjectId; /** * Checkin ID provided by the data provider. Must be unique across all checknis associated with * this project. */ @Persistent private Long externalId; @Persistent private String summary; /** * Directories where files were touched by this checkin. E.g., if files: * ADD alpha\beta\gamma\file1.txt * DELETE alpha\beta\gamma\file2.txt * EDIT alpha\beta\delta\file3.txt * * The set of directories would be { "alpha\beta\gamma", "alpha\beta\delta" }. */ @Persistent private Set<String> directoriesTouched = new HashSet<String>(); /** URL to identify view more information about the checkin. */ @Persistent private String changeUrl; /** Submitted, pending, etc. */ @Persistent private String state; /** Date it entered current state. */ @Persistent private Long stateDate; /** ID of the Attribute this checkin applies to, if any. */ @Persistent private Long targetAttributeId; /** ID of the Component this checkin applies to, if any. */ @Persistent private Long targetComponentId; /** ID of the Capability this checkin applies to, if any. */ @Persistent private Long targetCapabilityId; @Override public void setInternalId(Long internalId) { this.internalId = internalId; } @Override public Long getInternalId() { return internalId; } @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } @Override public Long getExternalId() { return externalId; } public void setSummary(String summary) { this.summary = summary; } public String getSummary() { return summary; } public void setDirectoriesTouched(Set<String> directoriesTouched) { this.directoriesTouched = directoriesTouched; } public Set<String> getDirectoriesTouched() { return directoriesTouched; } /** * @return the directories the checkin has touched as a comma separated list. */ public String getDirectoriesTouchedAsCommaSeparatedList() { return StringUtil.listToCsv(directoriesTouched); } public void addDirectoryTouched(String directory) { directoriesTouched.add(directory); } public void removeDirectoryTouched(String directory) { directoriesTouched.remove(directory); } public void setChangeUrl(String changeUrl) { this.changeUrl = changeUrl; } public String getChangeUrl() { return changeUrl; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { if (externalId == null) { return "Checkin (no id)"; } return ("Checkin #" + Long.toString(externalId)); } @Override public String getLinkUrl() { return changeUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append(summary); text.append("The following directories were touched: "); text.append(getDirectoriesTouchedAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return getTargetAttributeId() != null; } @Override public boolean isAttachedToCapability() { return getTargetCapabilityId() != null; } @Override public boolean isAttachedToComponent() { return getTargetComponentId() != null; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public DatumType getDatumType() { return DatumType.CHECKINS; } @Override public String getField(String field) { if ("Summary".equals(field)) { return summary; } else if ("Directories".equals(field)) { return getDirectoriesTouchedAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.util.List; /** * Supported data types. * * For each data type we keep track of how to refer to it in both a singular and plural sense. * We also track what parts of the datum support filtering. * * @author jimr@google.com (Jim Reardon) */ public enum DatumType { /** * Filtering is currently executed inside the {@link Filter} class. That, in turn, relies * upon each class that implements UploadedDatum to return any filterable field through the * <em>getField</em> method. */ BUGS("Bugs", "Bug", Lists.newArrayList("Title", "Path", "Labels")), TESTS("Tests", "Test", Lists.newArrayList("Title", "Labels")), CHECKINS("Checkins", "Checkin", Lists.newArrayList("Summary", "Directories")); private final String plural; private final String singular; private final List<String> filterTypes; DatumType(String plural, String singular, List<String> filterTypes) { this.plural = plural; this.singular = singular; this.filterTypes = filterTypes; } public String getPlural() { return plural; } public String getSingular() { return singular; } public List<String> getFilterTypes() { return filterTypes; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * An individual configuration option for a data request. For example, this is an example of * a data request option for a Bug * * name = "ComponentPath" * value = "\Testing\Tools\Test Analytics" * * This would import any bug under that component path. * * or * * name = "Hotlist" * value = "123123" * * This would import the bugs in hotlist 123123. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class DataRequestOption implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private String name; @Persistent private String value; @Persistent private DataRequest dataRequest; public DataRequestOption() { } public DataRequestOption(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getId() { return id; } public void setId(String id) { this.id = id; } public DataRequest getDataRequest() { return dataRequest; } public void setDataRequest(DataRequest dataRequest) { this.dataRequest = dataRequest; } }
Java
package com.google.testing.testify.risk.frontend.model; import java.util.List; /** * Interface that defines some commonality between items that have labels. For use in making * some functions generic. * * @author jimr@google.com (Jim Reardon) */ public interface HasLabels { public Long getId(); public long getParentProjectId(); public void setAccLabels(List<AccLabel> labels); public void addLabel(AccLabel label); public List<AccLabel> getAccLabels(); public AccElementType getElementType(); }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Capability. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Capability implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.CAPABILITY; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long capabilityId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); /** Parent Component. */ @Persistent private long componentId; /** Parent Attribute. */ @Persistent private long attributeId; @Persistent private FailureRate failureRate = FailureRate.NA; @Persistent private UserImpact userImpact = UserImpact.NA; @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); public Capability() { } /** * Constructs a new Capability. * * @param parentProjectId ID of the owning Project. * @param parentAttributeId Attribute ID of the parent Attribute. * @param parentComponentId Component ID of the parent Component. */ public Capability(long parentProjectId, long parentAttributeId, long parentComponentId) { this.parentProjectId = parentProjectId; this.componentId = parentComponentId; this.attributeId = parentAttributeId; } public Long getCapabilityId() { return capabilityId; } @Override public Long getId() { return getCapabilityId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } public void setCapabilityId(long capabilityId) { this.capabilityId = capabilityId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getComponentId() { return componentId; } public void setComponentId(long componentId) { this.componentId = componentId; } public long getAttributeId() { return attributeId; } public void setAttributeId(long attributeId) { this.attributeId = attributeId; } public UserImpact getUserImpact() { return userImpact; } public void setUserImpact(UserImpact userImpact) { this.userImpact = userImpact; } public FailureRate getFailureRate() { return failureRate; } public void setFailureRate(FailureRate failureRate) { this.failureRate = failureRate; } /** * @return the stable intersection key. {@See getCapabilityIntersectionKey} */ public int getCapabilityIntersectionKey() { return Capability.getCapabilityIntersectionKey(componentId, attributeId); } /** * Given a parent Component and Attribute return a random, but stable integer index. This * allows efficient lookup for Capabilities based on parent Components and Attribute pairs. * * @param component the parent component. * @param attribute the parent attribute. * @return a stable integer corresponding to the unique component / attribute pairing sutable * for placing Capability lists into a map. */ public static int getCapabilityIntersectionKey(Component component, Attribute attribute) { return Capability.getCapabilityIntersectionKey( component.getComponentId(), attribute.getAttributeId()); } /** * Computes a capability intersection key given the raw component and attribute IDs. */ private static int getCapabilityIntersectionKey(long componentId, long attributeId) { return Integer.valueOf((int) ((componentId << 16) ^ attributeId)); } public long getDisplayOrder() { return displayOrder; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public AccLabel addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(capabilityId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); return label; } public AccLabel addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(capabilityId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); return label; } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Represents an option for importing data and its options. For example, "Issue Tracker" would * be a DataSource and its parameters are options for search, such as "Owner". * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class DataSource implements Serializable { @SuppressWarnings("unused") @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private String name; @Persistent private List<String> parameters; @Persistent private Boolean internalOnly; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setInternalOnly(Boolean internalOnly) { this.internalOnly = internalOnly; } public Boolean isInternalOnly() { return internalOnly; } public void setParameters(List<String> parameters) { this.parameters = parameters; } public List<String> getParameters() { return parameters; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Configuration object for gathering data from an external source. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class DataRequest implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long requestId; @Persistent private long parentProjectId; /** Name of the external data source. For example, "Google Code Bug Database". */ @Persistent private String dataSourceName; /** A custom name if this is, for example, the "Other..." box. */ @Persistent private String customName; /** * List of options for this data request. For example, an option might be: * Component Path -> { Project/Component/Path } */ @Persistent(mappedBy = "dataRequest", defaultFetchGroup = "true") private List<DataRequestOption> dataRequestOptions = Lists.newArrayList(); public void setRequestId(Long requestId) { this.requestId = requestId; } public Long getRequestId() { return requestId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public long getParentProjectId() { return parentProjectId; } public void setDataSourceName(String dataSourceName) { this.dataSourceName = dataSourceName; } public String getDataSourceName() { return dataSourceName; } public void setCustomName(String customName) { this.customName = customName; } public String getCustomName() { return customName; } public List<DataRequestOption> getDataRequestOptions() { return dataRequestOptions; } public void setDataRequestOptions(List<DataRequestOption> dataRequestOptions) { this.dataRequestOptions = dataRequestOptions; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.Extension; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * An individual option for a filter. For example, this is an example of a FilterOption that * could appear on a bug: * * type = "Title" * value = "[security]" * * This would match any bug that has [security] inside its title. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class FilterOption implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) @Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true") private String id; @Persistent private String type; @Persistent private String value; @Persistent private Filter filter; public FilterOption() { } public FilterOption(String type, String value) { this.type = type; this.value = value; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; /** * Contains the status of the current user (logged in, logged out, email, et cetera). * * @author jimr@google.com (Jim Reardon) */ public class LoginStatus implements Serializable { private boolean isLoggedIn; private String url; private String email; public LoginStatus() { } /** Disable construction, see {@See LoggedInStatus} and {@See LoggedOutStatus}. */ public LoginStatus(boolean isLoggedIn, String url, String email) { this.isLoggedIn = isLoggedIn; this.url = url; this.email = email; } public void setUrl(String url) { this.url = url; } public String getUrl() { return url; } public void setEmail(String email) { this.email = email; } public String getEmail() { return email; } public void setIsLoggedIn(boolean isLoggedIn) { this.isLoggedIn = isLoggedIn; } public boolean getIsLoggedIn() { return isLoggedIn; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.testing.testify.risk.frontend.shared.util.StringUtil; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Generalized representation of a testcase to mitigate risk in a piece of software. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class TestCase implements Serializable, UploadedDatum { /** Unique identifier for this test case. */ @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long internalId; /** Project ID of the project the test case belongs to. */ @Persistent private Long parentProjectId; /** * Test case ID provided by the data provider. Must be unique across all bugs associated with this * project. */ @Persistent private Long externalId; /** Arbitrary title of the test case. */ @Persistent private String title; /** * Test cases have tags, which will be used to map it to Attributes, Components, Capabilities, * and so on. */ @Persistent private Set<String> tags = new HashSet<String>(); /** URL to identify view more information about the test case. */ @Persistent private String testCaseUrl; /** ID of the Attribute this testcase applies to, if any. */ @Persistent private Long targetAttributeId; /** ID of the Component this testcase applies to, if any. */ @Persistent private Long targetComponentId; /** ID of the Capability this testcase applies to, if any. */ @Persistent private Long targetCapabilityId; /** The status -- passed, failed, etc. */ @Persistent private String state; /** Result date. */ @Persistent private Long stateDate; @Override public void setInternalId(Long internalId) { this.internalId = internalId; } @Override public Long getInternalId() { return internalId; } @Override public void setParentProjectId(Long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public Long getParentProjectId() { return parentProjectId; } @Override public void setExternalId(Long externalId) { this.externalId = externalId; } @Override public Long getExternalId() { return externalId; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } public Set<String> getTags() { return tags; } public void setTags(Set<String> tags) { this.tags = tags; } public void removeTag(String tag) { tags.remove(tag); } public void addTag(String tag) { tags.add(tag); } /** * @return the tags associated with this test case as a comma separated list. */ public String getTagsAsCommaSeparatedList() { return StringUtil.listToCsv(tags); } public void setTestCaseUrl(String testCaseUrl) { this.testCaseUrl = testCaseUrl; } public String getTestCaseUrl() { return testCaseUrl; } @Override public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } @Override public Long getTargetAttributeId() { return targetAttributeId; } @Override public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } @Override public Long getTargetComponentId() { return targetComponentId; } @Override public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } @Override public Long getTargetCapabilityId() { return targetCapabilityId; } @Override public String getLinkText() { return title; } @Override public String getLinkUrl() { return testCaseUrl; } @Override public String getToolTip() { StringBuilder text = new StringBuilder(); text.append("Last Result: "); text.append(state == null ? "n/a" : state); text.append(" This testcase is labeled with the following tags: "); text.append(getTagsAsCommaSeparatedList()); return text.toString(); } @Override public boolean isAttachedToAttribute() { return getTargetAttributeId() != null; } @Override public boolean isAttachedToCapability() { return getTargetCapabilityId() != null; } @Override public boolean isAttachedToComponent() { return getTargetComponentId() != null; } @Override public String getState() { return state; } public void setState(String state) { this.state = state; } @Override public Long getStateDate() { return stateDate; } public void setStateDate(Long stateDate) { this.stateDate = stateDate; } @Override public DatumType getDatumType() { return DatumType.TESTS; } @Override public String getField(String field) { if ("Title".equals(field)) { return title; } else if ("Labels".equals(field)) { return getTagsAsCommaSeparatedList(); } return null; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enumeration for storing potential failure rates. * * @author chrsmith@google.com (Chris Smith) */ public enum UserImpact { NA (-2, "n/a"), MINIMAL (0, "Minimal"), SOME (1, "Some"), CONSIDERABLE (2, "Considerable"), MAXIMAL (3, "Maximal"); final int ordinal; final String description; private UserImpact(int ordinal, String description) { this.ordinal = ordinal; this.description = description; } public int getOrdinal() { return ordinal; } public String getDescription() { return description; } /** * Convert UserImpact.getDescription() into the original UserImpact instance. Enum.getValue * cannot be used because that requires the "ALL_CAPS" form of the value, rather than * the "User Friendly" getName version. */ public static UserImpact fromDescription(String name) { for (UserImpact impact : UserImpact.values()) { if (impact.getDescription().equals(name)) { return impact; } } return null; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Stores a boolean that determines if a ACC member has been signed off upon. This could be a * boolean on the ACC directly, but likely we will start to store much more data here -- an * audit trail, etc, so this will start out as a very small class in expectation to grow. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Signoff implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private long parentProjectId; @Persistent private AccElementType elementType; @Persistent private Long elementId; @Persistent private Boolean signedOff; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getParentProjectId() { return parentProjectId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public AccElementType getElementType() { return elementType; } public void setElementType(AccElementType elementType) { this.elementType = elementType; } public Long getElementId() { return elementId; } public void setElementId(Long elementId) { this.elementId = elementId; } public Boolean getSignedOff() { return signedOff; } public void setSignedOff(Boolean signedOff) { this.signedOff = signedOff; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Enum that lists all the possible element types in an ACC model. * * @author jimr@google.com (Jim Reardon) */ public enum AccElementType { ATTRIBUTE("Attribute"), COMPONENT("Component"), CAPABILITY("Capability"); private String friendlyName; private AccElementType(String friendlyName) { this.friendlyName = friendlyName; } public String getFriendlyName() { return friendlyName; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * Object for tracking user information. For example, starred/favorite projects. * * @author chrsmith@google.com (Chris Smith) */ @PersistenceCapable(detachable = "true") public class UserInfo implements Serializable { @SuppressWarnings("unused") @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; /** The User ID is the same ID returned by the App Engine UserService. */ @Persistent private String userId; /** * User's current email. This should not be keyed off of as the user's * email might change but still remain the same User ID. * * This can also be used to populate user id -- if user ID is null or missing, but email * is present, upon login the user ID will be populated. */ @Persistent private String currentEmail; /** * If a user is whitelisted, they will always have access to the application. Some users * will not require to be whitelisted, if they are permitted by default (ie, @google.com). */ @Persistent private Boolean isWhitelisted; /** List of IDs of starred projects. */ @Persistent private List<Long> starredProjects = Lists.newArrayList(); public void setUserId(String userId) { this.userId = userId; } public String getUserId() { return userId; } public void starProject(long projectId) { starredProjects.add(projectId); } public void unstarProject(long projectId) { starredProjects.remove(projectId); } public void setStarredProjects(List<Long> starredProjects) { this.starredProjects = starredProjects; } public List<Long> getStarredProjects() { return starredProjects; } public void setIsWhitelisted(boolean isWhitelisted) { this.isWhitelisted = isWhitelisted; } public Boolean getIsWhitelisted() { return isWhitelisted == null ? false : isWhitelisted; } public void setCurrentEmail(String currentEmail) { this.currentEmail = currentEmail; } public String getCurrentEmail() { return currentEmail; } }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import com.google.common.collect.Lists; import com.google.testing.testify.risk.frontend.model.DatumType; import java.io.Serializable; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * A representation of a filter to automatically assign data to ACC parts. * * A Filter will automatically assign data uploaded to specific ACC pieces. For example, * a Filter may say "assign any test labeled with 'Security' to the Security Attribute. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Filter implements Serializable { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long id; @Persistent private long parentProjectId; @Persistent private DatumType filterType; @Persistent private String filterConjunction; @Persistent(mappedBy = "filter", defaultFetchGroup = "true") private List<FilterOption> filterOptions = Lists.newArrayList(); @Persistent private Long targetAttributeId; @Persistent private Long targetComponentId; @Persistent private Long targetCapabilityId; /** * Creates a friendly title for this filter. * @return a title. */ public String getTitle() { return filterType.getSingular() + " Filter"; } public Long getId() { return id; } public void setId(long id) { this.id = id; } public long getParentProjectId() { return parentProjectId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } public Long getTargetAttributeId() { return targetAttributeId; } public void setTargetAttributeId(Long targetAttributeId) { this.targetAttributeId = targetAttributeId; } public Long getTargetComponentId() { return targetComponentId; } public void setTargetComponentId(Long targetComponentId) { this.targetComponentId = targetComponentId; } public Long getTargetCapabilityId() { return targetCapabilityId; } public void setTargetCapabilityId(Long targetCapabilityId) { this.targetCapabilityId = targetCapabilityId; } public DatumType getFilterType() { return filterType; } public void setFilterType(DatumType filterType) { this.filterType = filterType; } public List<FilterOption> getFilterOptions() { return filterOptions; } public void setFilterOptions(List<FilterOption> filterOptions) { this.filterOptions = filterOptions; } public void addFilterOption(String field, String value) { filterOptions.add(new FilterOption(field, value)); } public String getFilterConjunction() { return filterConjunction; } public void setFilterConjunction(String filterConjunction) { this.filterConjunction = filterConjunction; } public void apply(UploadedDatum item) { if (item.getDatumType() != filterType) { throw new IllegalArgumentException("Data types do not match; I filter " + filterType.getPlural() + " but received a " + item.getDatumType().getSingular()); } if (filterOptions.size() < 1 || (targetAttributeId == null && targetCapabilityId == null && targetComponentId == null)) { return; } boolean matchesAny = false; boolean matchesAll = true; for (FilterOption option : filterOptions) { String value = item.getField(option.getType()); if (value != null) { if (value.contains(option.getValue())) { matchesAny = true; } else { matchesAll = false; } } } if (matchesAll || ("any".equals(filterConjunction) && matchesAny)) { if (targetAttributeId != null) { item.setTargetAttributeId(targetAttributeId); } if (targetComponentId != null) { item.setTargetComponentId(targetComponentId); } if (targetCapabilityId != null) { item.setTargetCapabilityId(targetCapabilityId); } } } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.NotPersistent; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; /** * JDO object for Attribute. * * @author jimr@google.com (Jim Reardon) */ @PersistenceCapable(detachable = "true") public class Attribute implements Serializable, HasLabels { private static final AccElementType ELEMENT_TYPE = AccElementType.ATTRIBUTE; @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Long attributeId; @Persistent private long parentProjectId; @Persistent private String name; @Persistent private String description; /** * Ordering hint for views displaying Attributes. Lower values should be put higher in the list. * Note that value is NOT guaranteed to be unique or greater than zero. */ @Persistent private Long displayOrder = 0 - System.currentTimeMillis(); @NotPersistent private List<AccLabel> accLabels = new ArrayList<AccLabel>(); public Attribute() {} public Attribute(long parentProjectId) { this.parentProjectId = parentProjectId; } /** * @return the Attribute instance's attribute ID. It will be null if it has not been saved yet. */ public Long getAttributeId() { return attributeId; } @Override public Long getId() { return getAttributeId(); } @Override public AccElementType getElementType() { return ELEMENT_TYPE; } /** * Sets the Attribute's ID. Note this should only be called as a direct result of persisting * the Attribute in the data store. */ public void setAttributeId(long attributeId) { this.attributeId = attributeId; } public void setParentProjectId(long parentProjectId) { this.parentProjectId = parentProjectId; } @Override public long getParentProjectId() { return parentProjectId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setDisplayOrder(long displayOrder) { this.displayOrder = displayOrder; } public long getDisplayOrder() { return displayOrder; } @Override public List<AccLabel> getAccLabels() { return accLabels; } public AccLabel getAccLabel(String accLabelId) { for (AccLabel l : accLabels) { if (accLabelId.equals(l.getId())) { return l; } } return null; } @Override public void setAccLabels(List<AccLabel> labels) { this.accLabels = labels; } public void addLabel(String labelText) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(attributeId); label.setElementType(ELEMENT_TYPE); label.setLabelText(labelText); accLabels.add(label); } public void addLabel(String name, String value) { AccLabel label = new AccLabel(); label.setProjectId(parentProjectId); label.setElementId(attributeId); label.setElementType(ELEMENT_TYPE); label.setName(name); label.setValue(value); accLabels.add(label); } @Override public void addLabel(AccLabel label) { accLabels.add(label); } public void removeLabel(AccLabel label) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (label.getId() != null) { if (label.getId().equals(l.getId())) { i.remove(); } } else { if (label.getLabelText().equals(l.getLabelText())) { i.remove(); } } } } public void removeLabel(String labelText) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (labelText.equals(l.getLabelText())) { i.remove(); } } } public void removeLabel(String name, String value) { Iterator<AccLabel> i = accLabels.iterator(); AccLabel l; while (i.hasNext()) { l = i.next(); if (name.equals(l.getName()) && value.equals(l.getValue())) { i.remove(); } } } public void updateLabel(String oldLabelText, String newLabelText) { for (AccLabel l : accLabels) { if (oldLabelText.equals(l.getLabelText())) { l.setLabelText(newLabelText); } } } public void setDescription(String description) { this.description = description; } public String getDescription() { return description == null ? "" : description; } }
Java
// Copyright 2010 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; /** * Interface for surfacing inform from uploaded data to enable display. * * @author chrsmith@google.com (Chris Smith) */ public interface UploadedDatum { public DatumType getDatumType(); /** Returns the text for any links to this datum. */ public String getLinkText(); /** Returns an external URL to refer to the uploaded datum. */ public String getLinkUrl(); /** Returns a Tool Tip to display when hovering over the datum. */ public String getToolTip(); /** State, such as Open, Passed, Failed, etc. */ public String getState(); /** Date the item entered the state, eg: day it passed, date it was submitted. */ public Long getStateDate(); /** Methods for checking if the datum is attached to an Attribute, Component, or Capability. */ public boolean isAttachedToAttribute(); public boolean isAttachedToComponent(); public boolean isAttachedToCapability(); public void setTargetCapabilityId(Long targetCapabilityId); public Long getTargetCapabilityId(); public void setTargetAttributeId(Long targetAttributeId); public Long getTargetAttributeId(); public void setTargetComponentId(Long targetComponentId); public Long getTargetComponentId(); public Long getParentProjectId(); public void setParentProjectId(Long parentProjectId); public Long getExternalId(); public void setExternalId(Long externalId); public Long getInternalId(); public void setInternalId(Long internalId); /** Allows generic access for filtering. */ public String getField(String field); }
Java
// Copyright 2011 Google Inc. All Rights Reseved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.testing.testify.risk.frontend.model; import java.io.Serializable; /** * Simple pair class. * * @author jimr@google.com (Jim Reardon) */ public class Pair<A, B> implements Serializable { public final A first; public final B second; public Pair(A first, B second) { this.first = first; this.second = second; } public A getFirst() { return first; } public B getSecond() { return second; } }
Java