code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.tvremote;
import android.content.Context;
import android.media.AudioManager;
import android.view.MotionEvent;
/**
* The trackball logic.
*
*/
public final class TrackballHandler {
/**
* Direction of dpad events.
*/
enum Direction {
DOWN,
LEFT,
RIGHT,
UP
}
/**
* Modes this handler can be in.
*/
enum Mode {
DPAD,
SCROLL
}
/**
* Sound played on trackball Dpad event.
*/
private static final int SOUND_TRACKBALL = AudioManager.FX_KEY_CLICK;
/**
* Receives translated trackball events.
*/
interface Listener {
/**
* Called when a trackball event should be interpreted as a dpad event.
*
* @param direction represents the direction of the dpad event
*/
void onDirectionalEvent(Direction direction);
/**
* Called when a trackball event should be interpreted as a scrolling event.
*
* @param dx scrolling delta along the horizontal axis
* @param dy scrolling delta along the vertical axis
*/
void onScrollEvent(int dx, int dy);
/**
* Called when the trackball was clicked.
*/
void onClick();
}
private final Listener listener;
/**
* Parameter that controls the threshold for the amount of trackball motion
* needed to generate a directional event.
*/
private final float dpadThreshold;
private final int scrollAmount;
/**
* {@code true} if trackball events should be handled.
*/
private boolean enabled;
/**
* Mode this handler is currently in.
*/
private Mode mode;
/**
* Used to store the amounts of trackball motion observed.
*/
private float dpadAccuX, dpadAccuY;
/**
* Plays some sounds on trackball events.
*/
private AudioManager audioManager;
TrackballHandler(Listener listener, Context context) {
this.listener = listener;
this.mode = Mode.SCROLL;
dpadThreshold = (float) context.getResources().getInteger(
R.integer.dpad_threshold) / 100;
scrollAmount = context.getResources().getInteger(
R.integer.scroll_amount);
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public void setMode(Mode mode) {
this.mode = mode;
}
public void setAudioManager(AudioManager audioManager) {
this.audioManager = audioManager;
}
/**
* Should be called on every trackball event.
*/
public boolean onTrackballEvent(MotionEvent event) {
if (!enabled) {
return false;
}
switch (mode) {
case DPAD:
return onDpad(event);
case SCROLL:
return onScroll(event);
default:
return false;
}
}
/**
* Called to interpret an event as a scrolling event.
*/
private boolean onScroll(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
int deltaX = (int) (scrollAmount * event.getX()
* event.getXPrecision());
int deltaY = (int) (scrollAmount * event.getY()
* event.getYPrecision());
listener.onScrollEvent(deltaX, deltaY);
return true;
}
return false;
}
/**
* Called to interpret an event as a dpad event.
*/
private boolean onDpad(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
playSoundOnDPad();
listener.onClick();
resetMotionAccumulators();
return true;
}
dpadAccuX += event.getX();
dpadAccuY += event.getY();
if (Math.abs(dpadAccuX) > dpadThreshold) {
playSoundOnDPad();
listener.onDirectionalEvent(
dpadAccuX > 0 ? Direction.RIGHT : Direction.LEFT);
resetMotionAccumulators();
}
if (Math.abs(dpadAccuY) > dpadThreshold) {
playSoundOnDPad();
listener.onDirectionalEvent(
dpadAccuY > 0 ? Direction.DOWN : Direction.UP);
resetMotionAccumulators();
}
return true;
}
private void resetMotionAccumulators() {
dpadAccuX = 0;
dpadAccuY = 0;
}
/**
* Plays a sound when a Dpad event is performed.
*/
private void playSoundOnDPad() {
if (audioManager != null) {
audioManager.playSoundEffect(SOUND_TRACKBALL);
}
}
}
| Java |
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.tvremote;
import com.google.android.apps.tvremote.protocol.ICommandSender;
import java.util.ArrayList;
/**
* Connection management interface.
*
*/
public interface ConnectionManager {
/**
* Connection state change listener.
*/
public interface ConnectionListener {
/**
* Called when device finder is being requested.
*/
public void onShowDeviceFinder();
/**
* Called when connection process has started.
*/
public void onConnecting();
/**
* Called when connection succeeds.
*
* @param commandSender sender for given connection.
*/
public void onConnectionSuccessful(ICommandSender commandSender);
/**
* Called when remote target needs pairing.
*
* @param remoteDevice target to pair with.
*/
public void onNeedsPairing(RemoteDevice remoteDevice);
/**
* Called when remote gets disonnected from GTV.
*/
public void onDisconnected();
}
/**
* Setting new active target or {@code null} for no target.
*
* @param remoteDevice remote device.
*/
public void setTarget(RemoteDevice remoteDevice);
/**
* Connect with given connection listener.
*
* @param listener listener to be notified with connection state changes.
*/
public void connect(ConnectionListener listener);
/**
* Disconnect with given connection listener.
*
* @param listener listener to be unregistered.
*/
public void disconnect(ConnectionListener listener);
public void setKeepConnected(boolean keepConnected);
/**
* Returns current active remote device.
*
* @return remote device.
*/
public RemoteDevice getTarget();
/**
* Returns list of recently connected devices.
*
* @return recently connected devices.
*/
public ArrayList<RemoteDevice> getRecentlyConnected();
/**
* Notifies connection manager that pairing has finished.
*/
public void pairingFinished();
/**
* Notifies connection manager that device finder has finished.
*/
public void deviceFinderFinished();
/**
* Requests device finder.
*/
public void requestDeviceFinder();
}
| Java |
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.tvremote;
import com.google.android.apps.tvremote.TouchHandler.Mode;
import com.google.android.apps.tvremote.layout.SlidingLayout;
import com.google.android.apps.tvremote.util.Action;
import com.google.android.apps.tvremote.widget.HighlightView;
import com.google.android.apps.tvremote.widget.KeyCodeButton;
import com.google.android.apps.tvremote.widget.SoftDpad;
import com.google.anymote.Key;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Main screen of the remote controller activity.
*/
public class MainActivity extends BaseActivity
implements KeyCodeButton.KeyCodeHandler {
private static final String LOG_TAG = "RemoteActivity";
private HighlightView surface;
private final Handler handler;
/**
* The enum represents modes of the remote controller with
* {@link SlidingLayout} screens assignment. In conjunction with
* {@link ModeSelector} allows sliding between the screens.
*/
private enum RemoteMode {
TV(0, R.drawable.icon_04_touchpad_selector),
TOUCHPAD(1, R.drawable.icon_04_buttons_selector);
private final int screenId;
private final int switchButtonId;
RemoteMode(int screenId, int switchButtonId) {
this.screenId = screenId;
this.switchButtonId = switchButtonId;
}
}
/**
* Mode selector allow sliding across the modes, keeps currently selected mode
* information, and slides among the modes.
*/
private static final class ModeSelector {
private final SlidingLayout slidingLayout;
private final ImageButton imageButton;
private RemoteMode mode;
ModeSelector(
RemoteMode initialMode, SlidingLayout slidingLayout, ImageButton imageButton) {
mode = initialMode;
this.slidingLayout = slidingLayout;
this.imageButton = imageButton;
applyMode();
}
void slideNext() {
setMode(RemoteMode.TOUCHPAD.equals(mode) ? RemoteMode.TV : RemoteMode.TOUCHPAD);
}
void setMode(RemoteMode newMode) {
mode = newMode;
applyMode();
}
void applyMode() {
slidingLayout.snapToScreen(mode.screenId);
imageButton.setImageResource(mode.switchButtonId);
}
}
public MainActivity() {
handler = new Handler();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_touchpad_top);
surface = (HighlightView) findViewById(R.id.HighlightView);
LayoutInflater inflater = LayoutInflater.from(getBaseContext());
SlidingLayout slidingLayout = (SlidingLayout) findViewById(R.id.slider);
slidingLayout.addView(
inflater.inflate(R.layout.subview_playcontrol_tv, null), 0);
slidingLayout.addView(
inflater.inflate(R.layout.subview_touchpad, null), 1);
slidingLayout.setCurrentScreen(0);
ImageButton nextButton = (ImageButton) findViewById(R.id.button_next_page);
ImageButton keyboardButton =
(ImageButton) findViewById(R.id.button_keyboard);
ImageButton voiceButton = (ImageButton) findViewById(R.id.button_voice);
ImageButton searchButton = (ImageButton) findViewById(R.id.button_search);
ImageButton shortcutsButton =
(ImageButton) findViewById(R.id.button_shortcuts);
ImageButton liveTvButton = (ImageButton) findViewById(R.id.button_livetv);
final ModeSelector current =
new ModeSelector(RemoteMode.TV, slidingLayout, nextButton);
nextButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
current.slideNext();
}
});
liveTvButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
current.setMode(RemoteMode.TV);
}
});
keyboardButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showActivity(KeyboardActivity.class);
}
});
voiceButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showVoiceSearchActivity();
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Action.NAVBAR.execute(getCommands());
showActivity(KeyboardActivity.class);
}
});
shortcutsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
showActivity(ShortcutsActivity.class);
}
});
SoftDpad softDpad = (SoftDpad) findViewById(R.id.SoftDpad);
softDpad.setDpadListener(getDefaultDpadListener());
// Attach touch handler to the touchpad
new TouchHandler(
findViewById(R.id.touch_pad), Mode.POINTER_MULTITOUCH, getCommands());
flingIntent(getIntent());
}
@Override
protected void onDestroy() {
super.onDestroy();
}
public HighlightView getHighlightView() {
return surface;
}
// KeyCode handler implementation.
public void onRelease(Key.Code keyCode) {
getCommands().key(keyCode, Key.Action.UP);
}
public void onTouch(Key.Code keyCode) {
playClick();
getCommands().key(keyCode, Key.Action.DOWN);
}
private void playClick() {
((AudioManager) getSystemService(Context.AUDIO_SERVICE)).playSoundEffect(
AudioManager.FX_KEY_CLICK);
}
private void flingIntent(Intent intent) {
if (intent != null) {
if (Intent.ACTION_SEND.equals(intent.getAction())) {
String text = intent.getStringExtra(Intent.EXTRA_TEXT);
if (text != null) {
Uri uri = Uri.parse(text);
if (uri != null && ("http".equals(uri.getScheme())
|| "https".equals(uri.getScheme()))) {
getCommands().flingUrl(text);
} else {
Toast.makeText(
this, R.string.error_could_not_send_url, Toast.LENGTH_SHORT)
.show();
}
} else {
Log.w(LOG_TAG, "No URI to fling");
}
}
}
}
@Override
protected void onKeyboardOpened() {
showActivity(KeyboardActivity.class);
}
// SUBACTIVITIES
/**
* The activities that can be launched from the main screen.
* <p>
* These codes should not conflict with the request codes defined in
* {@link BaseActivity}.
*/
private enum SubActivity {
VOICE_SEARCH,
UNKNOWN;
public int code() {
return BaseActivity.FIRST_USER_CODE + ordinal();
}
public static SubActivity fromCode(int code) {
for (SubActivity activity : values()) {
if (code == activity.code()) {
return activity;
}
}
return UNKNOWN;
}
}
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
SubActivity activity = SubActivity.fromCode(requestCode);
switch (activity) {
case VOICE_SEARCH:
onVoiceSearchResult(resultCode, data);
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
// VOICE SEARCH
private void showVoiceSearchActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
startActivityForResult(intent, SubActivity.VOICE_SEARCH.code());
}
private void onVoiceSearchResult(int resultCode, Intent data) {
String searchQuery;
if ((resultCode == RESULT_CANCELED) || (data == null)) {
return;
}
ArrayList<String> queryResults =
data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if ((queryResults == null) || (queryResults.isEmpty())) {
Log.d(LOG_TAG, "No results from VoiceSearch server.");
return;
} else {
searchQuery = queryResults.get(0);
if (TextUtils.isEmpty(searchQuery)) {
Log.d(LOG_TAG, "Empty result from VoiceSearch server.");
return;
}
}
showVoiceSearchDialog(searchQuery);
}
private void showVoiceSearchDialog(final String query) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setNeutralButton(
R.string.voice_send, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
getCommands().string(query);
}
})
.setPositiveButton(
R.string.voice_search_send, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
getCommands().keyPress(Key.Code.KEYCODE_SEARCH);
// Send query delayed
handler.postDelayed(new Runnable() {
public void run() {
getCommands().string(query);
}
}, getResources().getInteger(R.integer.search_query_delay));
}
})
.setNegativeButton(
R.string.pairing_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setCancelable(true)
.setTitle(R.string.voice_dialog_label)
.setMessage(query);
builder.create().show();
}
}
| Java |
package pl.polidea.asl;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.security.InvalidParameterException;
import java.util.UUID;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Matrix;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
public class ScreenshotService extends Service {
/*
* Action name for intent used to bind to service.
*/
public static final String BIND = "pl.polidea.asl.ScreenshotService.BIND";
/*
* Name of the native process.
*/
private static final String NATIVE_PROCESS_NAME = "asl-native";
/*
* Port number used to communicate with native process.
*/
private static final int PORT = 42380;
/*
* Timeout allowed in communication with native process.
*/
private static final int TIMEOUT = 1000;
/*
* Directory where screenshots are being saved.
*/
private static final String SCREENSHOT_FOLDER = "/sdcard/screens/";
/*
* An implementation of interface used by clients to take screenshots.
*/
private final IScreenshotProvider.Stub mBinder = new IScreenshotProvider.Stub() {
@Override
public String takeScreenshot() throws RemoteException {
try {
return ScreenshotService.this.takeScreenshot();
}
catch(Exception e) { return null; }
}
@Override
public boolean isAvailable() throws RemoteException {
return isNativeRunning();
}
};
@Override
public void onCreate() {
Log.i("service", "Service created.");
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/*
* Checks whether the internal native application is running,
*/
private boolean isNativeRunning() {
try {
Socket sock = new Socket();
sock.connect(new InetSocketAddress("localhost", PORT), 10); // short timeout
}
catch (Exception e) {
return false;
}
return true;
// ActivityManager am = (ActivityManager)getSystemService(Service.ACTIVITY_SERVICE);
// List<ActivityManager.RunningAppProcessInfo> ps = am.getRunningAppProcesses();
//
// if (am != null) {
// for (ActivityManager.RunningAppProcessInfo rapi : ps) {
// if (rapi.processName.contains(NATIVE_PROCESS_NAME))
// // native application found
// return true;
// }
//
// }
// return false;
}
/*
* Internal class describing a screenshot.
*/
static final class Screenshot {
public Buffer pixels;
public int width;
public int height;
public int bpp;
public boolean isValid() {
if (pixels == null || pixels.capacity() == 0 || pixels.limit() == 0) return false;
if (width <= 0 || height <= 0) return false;
return true;
}
}
/*
* Determines whether the phone's screen is rotated.
*/
private int getScreenRotation() {
WindowManager wm = (WindowManager)getSystemService(WINDOW_SERVICE);
Display disp = wm.getDefaultDisplay();
// check whether we operate under Android 2.2 or later
try {
Class<?> displayClass = disp.getClass();
Method getRotation = displayClass.getMethod("getRotation");
int rot = ((Integer)getRotation.invoke(disp)).intValue();
switch (rot) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return 270;
default: return 0;
}
} catch (NoSuchMethodException e) {
// no getRotation() method -- fall back to getOrientation()
int orientation = disp.getOrientation();
// Sometimes you may get undefined orientation Value is 0
// simple logic solves the problem compare the screen
// X,Y Co-ordinates and determine the Orientation in such cases
if(orientation==Configuration.ORIENTATION_UNDEFINED){
Configuration config = getResources().getConfiguration();
orientation = config.orientation;
if(orientation==Configuration.ORIENTATION_UNDEFINED){
//if height and widht of screen are equal then
// it is square orientation
if(disp.getWidth()==disp.getHeight()){
orientation = Configuration.ORIENTATION_SQUARE;
}else{ //if widht is less than height than it is portrait
if(disp.getWidth() < disp.getHeight()){
orientation = Configuration.ORIENTATION_PORTRAIT;
}else{ // if it is not any of the above it will defineitly be landscape
orientation = Configuration.ORIENTATION_LANDSCAPE;
}
}
}
}
return orientation == 1 ? 0 : 90; // 1 for portrait, 2 for landscape
} catch (Exception e) {
return 0; // bad, I know ;P
}
}
/*
* Communicates with the native service and retrieves a screenshot from it
* as a 2D array of bytes.
*/
private Screenshot retreiveRawScreenshot() throws Exception {
try {
// connect to native application
Socket s = new Socket();
s.connect(new InetSocketAddress("localhost", PORT), TIMEOUT);
// send command to take screenshot
OutputStream os = s.getOutputStream();
os.write("SCREEN".getBytes("ASCII"));
// retrieve response -- first the size and BPP of the screenshot
InputStream is = s.getInputStream();
StringBuilder sb = new StringBuilder();
int c;
while ((c = is.read()) != -1) {
if (c == 0) break;
sb.append((char)c);
}
// parse it
String[] screenData = sb.toString().split(" ");
if (screenData.length >= 3) {
Screenshot ss = new Screenshot();
ss.width = Integer.parseInt(screenData[0]);
ss.height = Integer.parseInt(screenData[1]);
ss.bpp = Integer.parseInt(screenData[2]);
// retreive the screenshot
// (this method - via ByteBuffer - seems to be the fastest)
ByteBuffer bytes = ByteBuffer.allocate (ss.width * ss.height * ss.bpp / 8);
is = new BufferedInputStream(is); // buffering is very important apparently
is.read(bytes.array()); // reading all at once for speed
bytes.position(0); // reset position to the beginning of ByteBuffer
ss.pixels = bytes;
return ss;
}
}
catch (Exception e) {
throw new Exception(e);
}
finally {}
return null;
}
/*
* Saves given array of bytes into image file in the PNG format.
*/
private void writeImageFile(Screenshot ss, String file) {
if (ss == null || !ss.isValid()) throw new IllegalArgumentException();
if (file == null || file.length() == 0) throw new IllegalArgumentException();
// resolve screenshot's BPP to actual bitmap pixel format
Bitmap.Config pf;
switch (ss.bpp) {
case 16: pf = Config.RGB_565; break;
case 32: pf = Config.ARGB_8888; break;
default: pf = Config.ARGB_8888; break;
}
// create appropriate bitmap and fill it wit data
Bitmap bmp = Bitmap.createBitmap(ss.width, ss.height, pf);
bmp.copyPixelsFromBuffer(ss.pixels);
// handle the screen rotation
int rot = getScreenRotation();
if (rot != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(-rot);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
}
// save it in PNG format
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
throw new InvalidParameterException();
}
bmp.compress(CompressFormat.PNG, 100, fos);
}
/*
* Takes screenshot and saves to a file.
*/
private String takeScreenshot() throws IOException {
// make sure the path to save screens exists
File screensPath = new File(SCREENSHOT_FOLDER);
if (!screensPath.mkdirs()) return null;
// construct screenshot file name
StringBuilder sb = new StringBuilder();
sb.append(SCREENSHOT_FOLDER);
sb.append(Integer.toHexString(UUID.randomUUID().hashCode())); // hash code of UUID should be quite random yet short
sb.append(".png");
String file = sb.toString();
// fetch the screen and save it
Screenshot ss = null;
try {
ss = retreiveRawScreenshot();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
writeImageFile(ss, file);
return file;
}
}
| Java |
package pl.polidea.asl.demo;
import pl.polidea.asl.*;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources.NotFoundException;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.graphics.*;
public class ScreenshotDemo extends Activity {
/*
* The ImageView used to display taken screenshots.
*/
private ImageView imgScreen;
private ServiceConnection aslServiceConn = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
aslProvider = IScreenshotProvider.Stub.asInterface(service);
}
};
private IScreenshotProvider aslProvider = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgScreen = (ImageView)findViewById(R.id.imgScreen);
Button btn = (Button)findViewById(R.id.btnTakeScreenshot);
btn.setOnClickListener(btnTakeScreenshot_onClick);
// connect to ASL service
//Intent intent = new Intent(ScreenshotService.class.getName());
Intent intent = new Intent();
intent.setClass(this, ScreenshotService.class);
//intent.addCategory(Intent.ACTION_DEFAULT);
bindService (intent, aslServiceConn, Context.BIND_AUTO_CREATE);
}
@Override
public void onDestroy() {
unbindService(aslServiceConn);
super.onDestroy();
}
private View.OnClickListener btnTakeScreenshot_onClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (aslProvider == null)
Toast.makeText(ScreenshotDemo.this, R.string.n_a, Toast.LENGTH_SHORT).show();
else if (!aslProvider.isAvailable())
Toast.makeText(ScreenshotDemo.this, R.string.native_n_a, Toast.LENGTH_SHORT).show();
else {
String file = aslProvider.takeScreenshot();
if (file == null)
Toast.makeText(ScreenshotDemo.this, R.string.screenshot_error, Toast.LENGTH_SHORT).show();
else {
Toast.makeText(ScreenshotDemo.this, R.string.screenshot_ok, Toast.LENGTH_SHORT).show();
Bitmap screen = BitmapFactory.decodeFile(file);
imgScreen.setImageBitmap(screen);
}
}
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (RemoteException e) {
// squelch
}
}
};
} | Java |
// Copyright 2010 Google Inc. All Rights Reserved
package com.google.testing.testify.risk.frontend.client.presenter;
/**
* Base Presenter for all application pages.
*
* @author jimr@google.com (Jim Reardon)
*/
public abstract class BasePagePresenter implements TaPagePresenter {
/**
* Refresh the view, including page data.
*
* By default, pages won't care about passed in page data and thus short circuit over to the
* no-parameter refreshView unless explicitly implemented by the page presenter.
*
* @param pageData the parameter data for this page.
* */
@Override
public void refreshView(String pageData) {
refreshView();
}
}
| 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.presenter;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.event.ProjectChangedEvent;
import com.google.testing.testify.risk.frontend.client.view.ProjectSettingsView;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
import java.util.List;
/**
* Presenter for the ProjectSettings widget.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ProjectSettingsPresenter
extends BasePagePresenter
implements ProjectSettingsView.Presenter, TaPagePresenter {
private final Project project;
private final ProjectRpcAsync projectService;
private final UserRpcAsync userService;
private final ProjectSettingsView view;
private final EventBus eventBus;
/**
* Constructs the presenter.
*/
public ProjectSettingsPresenter(Project project, ProjectRpcAsync projectService,
UserRpcAsync userService, ProjectSettingsView view, EventBus eventBus) {
this.project = project;
this.projectService = projectService;
this.userService = userService;
this.view = view;
this.eventBus = eventBus;
refreshView();
}
/**
* Query the database for project information and populate UI fields.
*/
@Override
public void refreshView() {
view.setPresenter(this);
view.setProjectSettings(project);
userService.getAccessLevel(project.getProjectId(),
new TaCallback<ProjectAccess>("Checking User Access") {
@Override
public void onSuccess(ProjectAccess result) {
view.enableProjectEditing(result);
}
});
}
/** Returns the underlying view. */
@Override
public Widget getView() {
return view.asWidget();
}
@Override
public ProjectRpcAsync getProjectService() {
return projectService;
}
@Override
public long getProjectId() {
return project.getProjectId();
}
/**
* To be called by the View when the user performs the updateProjectInfo action.
*/
@Override
public void onUpdateProjectInfoClicked(
String name, String description,
List<String> projectOwners, List<String> projectEditors, List<String> projectViewers,
boolean isPublicalyVisible) {
project.setName(name);
project.setDescription(description);
project.setIsPubliclyVisible(isPublicalyVisible);
project.setProjectOwners(projectOwners);
project.setProjectEditors(projectEditors);
project.setProjectViewers(projectViewers);
projectService.updateProject(project,
new TaCallback<Void>("Updating Project") {
@Override
public void onSuccess(Void result) {
view.showSaved();
eventBus.fireEvent(new ProjectChangedEvent(project));
}
});
}
@Override
public void removeProject() {
projectService.removeProject(project, TaCallback.getNoopCallback());
}
}
| 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.presenter;
import com.google.testing.testify.risk.frontend.client.view.ComponentView;
import com.google.testing.testify.risk.frontend.client.view.ComponentsView;
import com.google.testing.testify.risk.frontend.model.AccLabel;
import com.google.testing.testify.risk.frontend.model.Component;
/**
* Presenter for a single Component.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ComponentPresenter implements ComponentView.Presenter {
private Component targetComponent;
private final ComponentView view;
private final ComponentsView.Presenter parentPresenter;
public ComponentPresenter(Component component, ComponentView view,
ComponentsView.Presenter parentPresenter) {
this.targetComponent = component;
this.view = view;
this.parentPresenter = parentPresenter;
view.setPresenter(this);
refreshView();
}
/**
* Refreshes UI elements of the View.
*/
@Override
public void refreshView() {
view.setComponentName(targetComponent.getName());
view.setDescription(targetComponent.getDescription());
if (targetComponent.getComponentId() != null) {
view.setComponentId(targetComponent.getComponentId());
}
view.setComponentLabels(targetComponent.getAccLabels());
}
@Override
public void refreshView(Component component) {
this.targetComponent = component;
refreshView();
}
@Override
public long getComponentId() {
return targetComponent.getComponentId();
}
@Override
public long getProjectId() {
return targetComponent.getParentProjectId();
}
@Override
public void updateSignoff(boolean newValue) {
parentPresenter.updateSignoff(targetComponent, newValue);
}
@Override
public void onDescriptionEdited(String description) {
targetComponent.setDescription(description);
parentPresenter.updateComponent(targetComponent);
}
@Override
public void onRename(String newComponentName) {
targetComponent.setName(newComponentName);
parentPresenter.updateComponent(targetComponent);
}
@Override
public void onRemove() {
view.hide();
parentPresenter.removeComponent(targetComponent);
}
@Override
public void onAddLabel(String label) {
targetComponent.addLabel(label);
parentPresenter.updateComponent(targetComponent);
}
@Override
public void onUpdateLabel(AccLabel label, String newText) {
label = targetComponent.getAccLabel(label.getId());
label.setLabelText(newText);
parentPresenter.updateComponent(targetComponent);
}
@Override
public void onRemoveLabel(AccLabel label) {
targetComponent.removeLabel(label);
parentPresenter.updateComponent(targetComponent);
}
}
| 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.presenter;
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.DataRequestOption;
import com.google.testing.testify.risk.frontend.model.DataSource;
import java.util.List;
/**
* Presenter for an individual DataRequest view.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class DataRequestPresenter implements DataRequestView.Presenter {
private final DataRequest targetRequest;
private final DataSource dataSource;
private final DataRequestView view;
private final ConfigureDataView.Presenter parentPresenter;
public DataRequestPresenter(DataRequest request, DataSource dataSource, DataRequestView view,
ConfigureDataView.Presenter parentPresenter) {
this.dataSource = dataSource;
this.targetRequest = request;
this.view = view;
this.parentPresenter = parentPresenter;
refreshView();
}
/**
* Refreshes UI elements of the View.
*/
@Override
public void refreshView() {
view.setPresenter(this);
String dataSourceName = targetRequest.getDataSourceName();
view.setDataSourceName(dataSourceName);
view.setDataSourceParameters(dataSource.getParameters(), targetRequest.getDataRequestOptions());
}
@Override
public void onUpdate(List<DataRequestOption> newParameters) {
targetRequest.setDataRequestOptions(newParameters);
parentPresenter.updateDataRequest(targetRequest);
}
@Override
public void onRemove() {
view.hide();
parentPresenter.deleteDataRequest(targetRequest);
}
}
| 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.presenter;
import com.google.common.collect.Lists;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedEvent;
import com.google.testing.testify.risk.frontend.client.event.ProjectHasNoElementsEvent;
import com.google.testing.testify.risk.frontend.client.view.ComponentsView;
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.Component;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.model.Signoff;
import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
import java.util.Collection;
import java.util.List;
/**
* Presenter for the Components page.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ComponentsPresenter extends BasePagePresenter
implements TaPagePresenter, ComponentsView.Presenter {
private final Project project;
private final ProjectRpcAsync projectService;
private final UserRpcAsync userService;
private final DataRpcAsync dataService;
private final ComponentsView view;
private final EventBus eventBus;
private final Collection<String> projectLabels = Lists.newArrayList();
/**
* Constructs the presenter.
*/
public ComponentsPresenter(
Project project, ProjectRpcAsync projectService, UserRpcAsync userService,
DataRpcAsync dataService, ComponentsView view, EventBus eventBus) {
this.project = project;
this.projectService = projectService;
this.userService = userService;
this.dataService = dataService;
this.view = view;
this.eventBus = eventBus;
refreshView();
}
/**
* Query the database for project information and populate UI fields.
*/
@Override
public void refreshView() {
view.setPresenter(this);
userService.hasEditAccess(project.getProjectId(),
new TaCallback<Boolean>("Checking User Access") {
@Override
public void onSuccess(Boolean result) {
// Assume the user already has VIEW access, otherwise the RPC service wouldn't have
// served the Project object in the first place.
if (result) {
view.enableEditing();
}
}
});
projectService.getProjectComponents(project.getProjectId(),
new TaCallback<List<Component>>("Querying Components") {
@Override
public void onSuccess(List<Component> result) {
if (result.size() == 0) {
eventBus.fireEvent(
new ProjectHasNoElementsEvent(project, AccElementType.COMPONENT));
}
view.setProjectComponents(result);
}
});
dataService.getSignoffsByType(project.getProjectId(), AccElementType.COMPONENT,
new TaCallback<List<Signoff>>("Retrieving signoff data") {
@Override
public void onSuccess(List<Signoff> results) {
view.setSignoffs(results);
}
});
projectService.getLabels(project.getProjectId(),
new TaCallback<List<AccLabel>>("Loading labels") {
@Override
public void onSuccess(List<AccLabel> result) {
for (AccLabel l : result) {
projectLabels.add(l.getLabelText());
}
view.setProjectLabels(projectLabels);
}
});
}
/** Returns the underlying view. */
@Override
public Widget getView() {
return view.asWidget();
}
@Override
public long getProjectId() {
return project.getProjectId();
}
@Override
public void createComponent(final Component component) {
projectService.createComponent(component,
new TaCallback<Long>("Creating Component") {
@Override
public void onSuccess(Long result) {
component.setComponentId(result);
refreshView();
eventBus.fireEvent(new ProjectElementAddedEvent(component));
}
});
}
/**
* Updates the given component in the database.
*/
@Override
public void updateComponent(Component componentToUpdate) {
projectService.updateComponent(componentToUpdate,
new TaCallback<Component>("updating component") {
@Override
public void onSuccess(Component result) {
view.refreshComponent(result);
}
});
}
@Override
public void updateSignoff(Component component, boolean newSignoff) {
dataService.setSignedOff(component.getParentProjectId(), AccElementType.COMPONENT,
component.getComponentId(), newSignoff, TaCallback.getNoopCallback());
}
/**
* Removes the given component from the Project.
*/
@Override
public void removeComponent(Component componentToRemove) {
projectService.removeComponent(componentToRemove,
new TaCallback<Void>("Removing Component") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
@Override
public ProjectRpcAsync getProjectService() {
return projectService;
}
@Override
public void reorderComponents(List<Long> newOrder) {
projectService.reorderComponents(
project.getProjectId(), newOrder,
new TaCallback<Void>("Reordering Comonents") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
}
| 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.presenter;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.view.RiskView;
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.shared.rpc.ProjectRpcAsync;
import java.util.List;
/**
* Base class for Presenters surfacing views on top of Risk and/or Risk Mitigations.
*
* @author chrsmith@google.com (Chris)
*/
public abstract class RiskPresenter extends BasePagePresenter {
protected final ProjectRpcAsync projectService;
protected final RiskView view;
protected final Project project;
public RiskPresenter(Project project, ProjectRpcAsync projectService, RiskView view) {
this.project = project;
this.projectService = projectService;
this.view = view;
}
/**
* Refreshes the view based on data obtained from the Project Service.
*/
public void refreshBaseView() {
final long projectId = project.getProjectId();
projectService.getProjectAttributes(projectId,
new TaCallback<List<Attribute>>("Querying Attributes") {
@Override
public void onSuccess(List<Attribute> result) {
view.setAttributes(result);
}
});
projectService.getProjectComponents(projectId,
new TaCallback<List<Component>>("Querying Components") {
@Override
public void onSuccess(List<Component> result) {
view.setComponents(result);
}
});
projectService.getProjectCapabilities(projectId,
new TaCallback<List<Capability>>("Querying Capabilities") {
@Override
public void onSuccess(List<Capability> result) {
view.setCapabilities(result);
}
});
}
}
| 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.presenter;
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.Filter;
import com.google.testing.testify.risk.frontend.model.FilterOption;
import java.util.List;
import java.util.Map;
/**
* Presenter for an individual Filter.
*
* @author jimr@google.com (Jim Reardon)
*/
public class FilterPresenter implements FilterView.Presenter {
private final Filter filter;
private final FilterView view;
private final ConfigureFiltersView.Presenter presenter;
public FilterPresenter(Filter filter, Map<String, Long> attributes, Map<String, Long> components,
Map<String, Long> capabilities, FilterView view, ConfigureFiltersView.Presenter presenter) {
this.filter = filter;
this.view = view;
this.presenter = presenter;
view.setPresenter(this);
view.setAttributes(attributes);
view.setComponents(components);
view.setCapabilities(capabilities);
refreshView();
}
@Override
public void refreshView() {
view.setFilterTitle(filter.getTitle());
view.setFilterOptionChoices(filter.getFilterType().getFilterTypes());
view.setFilterSettings(filter.getFilterOptions(), filter.getFilterConjunction(),
filter.getTargetAttributeId(), filter.getTargetComponentId(),
filter.getTargetCapabilityId());
}
@Override
public void onUpdate(List<FilterOption> newOptions, String conjunction, Long attribute,
Long component, Long capability) {
filter.setFilterOptions(newOptions);
filter.setFilterConjunction(conjunction);
filter.setTargetAttributeId(attribute);
filter.setTargetCapabilityId(capability);
filter.setTargetComponentId(component);
presenter.updateFilter(filter);
}
@Override
public void onRemove() {
view.hide();
presenter.deleteFilter(filter);
}
}
| Java |
// Copyright 2010 Google Inc.
package com.google.testing.testify.risk.frontend.client.presenter;
import com.google.gwt.user.client.ui.Widget;
/**
* Base interface for all Presenters for Test Analytics pages.
*
* @author chrsmith@google.com (Chris)
*/
public interface TaPagePresenter {
/** Refreshes the current view. Typically by querying the datastore and updating UI elements. */
public void refreshView();
/** Allows data to be passed in while refreshing the view. */
public void refreshView(String pageData);
/** Returns the underlying View. */
public Widget getView();
}
| 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.presenter;
import com.google.common.collect.Lists;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedEvent;
import com.google.testing.testify.risk.frontend.client.view.CapabilitiesView;
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.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
import java.util.Collection;
import java.util.List;
/**
* Presenter for the CapabilitiesGrid widget.
* {@See com.google.testing.testify.risk.frontend.client.view.CapabilitiesGridView}
*
* @author jimr@google.com (Jim Reardon)
*/
public class CapabilitiesPresenter
extends BasePagePresenter implements CapabilitiesView.Presenter, TaPagePresenter {
private final Project project;
private final ProjectRpcAsync projectService;
private final UserRpcAsync userService;
private final CapabilitiesView view;
private final EventBus eventBus;
public CapabilitiesPresenter(
Project project, ProjectRpcAsync projectService, UserRpcAsync userService,
CapabilitiesView view, EventBus eventBus) {
this.project = project;
this.projectService = projectService;
this.userService = userService;
this.view = view;
this.eventBus = eventBus;
refreshView();
}
/**
* Refreshes the view based on data obtained from the Project Service.
*/
@Override
public void refreshView() {
view.setPresenter(this);
userService.hasEditAccess(project.getProjectId(),
new TaCallback<Boolean>("checking user access") {
@Override
public void onSuccess(Boolean result) {
// Assume the user already has VIEW access, otherwise the RPC service wouldn't have
// served the Project object in the first place.
view.setEditable(result);
}
});
projectService.getProjectAttributes(project.getProjectId(),
new TaCallback<List<Attribute>>("querying attributes") {
@Override
public void onSuccess(List<Attribute> result) {
view.setAttributes(result);
}
});
projectService.getProjectComponents(project.getProjectId(),
new TaCallback<List<Component>>("querying components") {
@Override
public void onSuccess(List<Component> result) {
view.setComponents(result);
}
});
projectService.getProjectCapabilities(project.getProjectId(),
new TaCallback<List<Capability>>("querying capabilities") {
@Override
public void onSuccess(List<Capability> result) {
view.setCapabilities(result);
}
});
projectService.getLabels(project.getProjectId(),
new TaCallback<List<AccLabel>>("querying components") {
@Override
public void onSuccess(List<AccLabel> result) {
Collection<String> labels = Lists.newArrayList();
for (AccLabel l : result) {
labels.add(l.getLabelText());
}
view.setProjectLabels(labels);
}
});
}
@Override
public void onAddCapability(final Capability capabilityToAdd) {
projectService.createCapability(capabilityToAdd,
new TaCallback<Capability>("creating capability") {
@Override
public void onSuccess(Capability result) {
eventBus.fireEvent(
new ProjectElementAddedEvent(result));
view.addCapability(result);
}
});
}
@Override
public void onUpdateCapability(Capability capabilityToUpdate) {
projectService.updateCapability(capabilityToUpdate, TaCallback.getNoopCallback());
}
@Override
public void onRemoveCapability(Capability capabilityToRemove) {
projectService.removeCapability(capabilityToRemove, TaCallback.getNoopCallback());
}
@Override
public void reorderCapabilities(List<Long> ids) {
projectService.reorderCapabilities(project.getProjectId(), ids,
TaCallback.getNoopCallback());
}
/** Returns the underlying view. */
@Override
public Widget getView() {
return 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.presenter;
import com.google.testing.testify.risk.frontend.client.view.AttributeView;
import com.google.testing.testify.risk.frontend.client.view.AttributesView;
import com.google.testing.testify.risk.frontend.model.AccLabel;
import com.google.testing.testify.risk.frontend.model.Attribute;
/**
* Presenter for a single Attribute.
*
* @author jimr@google.com (Jim Reardon)
*/
public class AttributePresenter implements AttributeView.Presenter {
private Attribute targetAttribute;
private final AttributeView view;
private final AttributesView.Presenter parentPresenter;
public AttributePresenter(Attribute targetAttribute, AttributeView view,
AttributesView.Presenter parentPresenter) {
this.targetAttribute = targetAttribute;
this.view = view;
this.parentPresenter = parentPresenter;
view.setPresenter(this);
refreshView();
}
/**
* Refreshes UI elements of the View.
*/
@Override
public void refreshView() {
view.setAttributeName(targetAttribute.getName());
view.setDescription(targetAttribute.getDescription());
if (targetAttribute.getAttributeId() != null) {
view.setAttributeId(targetAttribute.getAttributeId());
}
view.setLabels(targetAttribute.getAccLabels());
}
@Override
public void refreshView(Attribute attribute) {
this.targetAttribute = attribute;
refreshView();
}
@Override
public long getAttributeId() {
return targetAttribute.getAttributeId();
}
@Override
public long getProjectId() {
return targetAttribute.getParentProjectId();
}
@Override
public void updateSignoff(boolean newValue) {
parentPresenter.updateSignoff(targetAttribute, newValue);
}
@Override
public void onDescriptionEdited(String description) {
targetAttribute.setDescription(description);
parentPresenter.updateAttribute(targetAttribute);
}
@Override
public void onRename(String newAttributeName) {
targetAttribute.setName(newAttributeName);
parentPresenter.updateAttribute(targetAttribute);
}
@Override
public void onRemove() {
view.hide();
parentPresenter.removeAttribute(targetAttribute);
}
@Override
public void onAddLabel(String label) {
targetAttribute.addLabel(label);
parentPresenter.updateAttribute(targetAttribute);
}
@Override
public void onUpdateLabel(AccLabel label, String newText) {
label = targetAttribute.getAccLabel(label.getId());
label.setLabelText(newText);
parentPresenter.updateAttribute(targetAttribute);
}
@Override
public void onRemoveLabel(AccLabel label) {
targetAttribute.removeLabel(label);
parentPresenter.updateAttribute(targetAttribute);
}
}
| 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.presenter;
import com.google.common.collect.Lists;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.view.CapabilityDetailsView;
import com.google.testing.testify.risk.frontend.model.AccElementType;
import com.google.testing.testify.risk.frontend.model.AccLabel;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Bug;
import com.google.testing.testify.risk.frontend.model.Capability;
import com.google.testing.testify.risk.frontend.model.Checkin;
import com.google.testing.testify.risk.frontend.model.Component;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.model.TestCase;
import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
import java.util.Collection;
import java.util.List;
/**
* Presenter for the details of a single capability.
*
* @author jimr@google.com (Jim Reardon)
*/
public class CapabilityDetailsPresenter extends BasePagePresenter
implements CapabilityDetailsView.Presenter {
protected final Project project;
protected final ProjectRpcAsync projectService;
protected final UserRpcAsync userService;
protected final DataRpcAsync dataService;
protected final CapabilityDetailsView view;
protected String pageData;
private Long capabilityId;
public CapabilityDetailsPresenter(Project project, ProjectRpcAsync projectService,
DataRpcAsync dataService, UserRpcAsync userService,
CapabilityDetailsView view) {
this.project = project;
this.projectService = projectService;
this.dataService = dataService;
this.userService = userService;
this.view = view;
view.setPresenter(this);
}
@Override
public void refreshView() {
final long projectId = project.getProjectId();
// Tell view to expect an entire reload of data.
view.reset();
userService.hasEditAccess(projectId,
new TaCallback<Boolean>("Querying user permissions") {
@Override
public void onSuccess(Boolean result) {
if (result == true) {
view.makeEditable();
}
}
});
projectService.getProjectAttributes(projectId,
new TaCallback<List<Attribute>>("Querying Attributes") {
@Override
public void onSuccess(List<Attribute> result) {
view.setAttributes(result);
}
});
projectService.getLabels(projectId,
new TaCallback<List<AccLabel>>("Querying Components") {
@Override
public void onSuccess(List<AccLabel> result) {
Collection<String> labels = Lists.newArrayList();
for (AccLabel l : result) {
labels.add(l.getLabelText());
}
view.setProjectLabels(labels);
}
});
projectService.getProjectComponents(projectId,
new TaCallback<List<Component>>("Querying Components") {
@Override
public void onSuccess(List<Component> result) {
view.setComponents(result);
}
});
projectService.getCapabilityById(projectId, capabilityId,
new TaCallback<Capability>("Querying capability") {
@Override
public void onSuccess(Capability result) {
view.setCapability(result);
}
});
dataService.isSignedOff(AccElementType.CAPABILITY, capabilityId,
new TaCallback<Boolean>("Getting signoff status") {
@Override
public void onSuccess(Boolean result) {
view.setSignoff(result == null ? false : result);
}
});
dataService.getProjectBugsById(projectId,
new TaCallback<List<Bug>>("Querying Bugs") {
@Override
public void onSuccess(List<Bug> result) {
view.setBugs(result);
}
});
dataService.getProjectTestCasesById(projectId,
new TaCallback<List<TestCase>>("Querying Tests") {
@Override
public void onSuccess(List<TestCase> result) {
view.setTests(result);
}
});
dataService.getProjectCheckinsById(projectId,
new TaCallback<List<Checkin>>("Querying Checkins") {
@Override
public void onSuccess(List<Checkin> result) {
view.setCheckins(result);
}
});
}
@Override
public void assignBugToCapability(long capabilityId, long bugId) {
dataService.updateBugAssociations(bugId, -1, -1, capabilityId,
new TaCallback<Void>("assigning bug to capability"));
}
@Override
public void assignCheckinToCapability(long capabilityId, long checkinId) {
dataService.updateCheckinAssociations(checkinId, -1, -1, capabilityId,
new TaCallback<Void>("assigning checkin to capability"));
}
@Override
public void assignTestCaseToCapability(long capabilityId, long testId) {
dataService.updateTestAssociations(testId, -1, -1, capabilityId,
new TaCallback<Void>("assigning test to capability"));
}
@Override
public void refreshView(String pageData) {
try {
capabilityId = Long.parseLong(pageData);
} catch (NumberFormatException e) {
Window.alert("Cannot refresh capability details page, invalid capbility ID.");
}
refreshView();
}
@Override
public Widget getView() {
return view.asWidget();
}
@Override
public void updateCapability(Capability capability) {
projectService.updateCapability(capability, new TaCallback<Void>("updating capability"));
}
@Override
public void setSignoff(long capabilityId, boolean isSignedOff) {
dataService.setSignedOff(project.getProjectId(), AccElementType.CAPABILITY, capabilityId,
isSignedOff, new TaCallback<Void>("setting signoff status"));
}
}
| 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.presenter;
import com.google.common.collect.Maps;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.view.ConfigureFiltersView;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Capability;
import com.google.testing.testify.risk.frontend.model.Component;
import com.google.testing.testify.risk.frontend.model.Filter;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import java.util.HashMap;
import java.util.List;
/**
* Presenter for Filter list and creating filters.
*
* @author jimr@google.com (Jim Reardon)
*/
public class ConfigureFiltersPresenter extends BasePagePresenter implements TaPagePresenter,
ConfigureFiltersView.Presenter {
private final Project project;
private final DataRpcAsync dataService;
private final ProjectRpcAsync projectService;
private final ConfigureFiltersView view;
public ConfigureFiltersPresenter(Project project, DataRpcAsync dataService,
ProjectRpcAsync projectService, ConfigureFiltersView view) {
this.project = project;
this.dataService = dataService;
this.projectService = projectService;
this.view = view;
refreshView();
}
@Override
public Widget getView() {
return view.asWidget();
}
@Override
public void refreshView() {
view.setPresenter(this);
dataService.getFilters(project.getProjectId(),
new TaCallback<List<Filter>>("Getting filters") {
@Override
public void onSuccess(List<Filter> result) {
view.setFilters(result);
}
});
projectService.getProjectAttributes(project.getProjectId(),
new TaCallback<List<Attribute>>("Getting attributes") {
@Override
public void onSuccess(List<Attribute> result) {
HashMap<String, Long> map = Maps.newHashMap();
for (Attribute attribute : result) {
map.put(attribute.getName(), attribute.getAttributeId());
}
view.setAttributes(map);
}
});
projectService.getProjectComponents(project.getProjectId(),
new TaCallback<List<Component>>("Getting components") {
@Override
public void onSuccess(List<Component> result) {
HashMap<String, Long> map = Maps.newHashMap();
for (Component component : result) {
map.put(component.getName(), component.getComponentId());
}
view.setComponents(map);
}
});
projectService.getProjectCapabilities(project.getProjectId(),
new TaCallback<List<Capability>>("Getting capabilities") {
@Override
public void onSuccess(List<Capability> result) {
HashMap<String, Long> map = Maps.newHashMap();
for (Capability capability : result) {
map.put(capability.getName(), capability.getCapabilityId());
}
view.setCapabilities(map);
}
});
}
@Override
public void addFilter(final Filter newFilter) {
newFilter.setParentProjectId(project.getProjectId());
dataService.addFilter(newFilter,
new TaCallback<Long>("Adding new filter") {
@Override
public void onSuccess(Long result) {
newFilter.setId(result);
refreshView();
}
});
}
@Override
public void deleteFilter(Filter filterToDelete) {
dataService.removeFilter(filterToDelete,
new TaCallback<Void>("Deleting filter") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
@Override
public void updateFilter(Filter filterToUpdate) {
dataService.updateFilter(filterToUpdate, TaCallback.getNoopCallback());
}
}
| 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.presenter;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.view.ConfigureDataView;
import com.google.testing.testify.risk.frontend.model.DataRequest;
import com.google.testing.testify.risk.frontend.model.DataSource;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync;
import java.util.List;
/**
* Presenter for the Configure Data page.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ConfigureDataPresenter extends BasePagePresenter
implements TaPagePresenter, ConfigureDataView.Presenter {
private final Project project;
private final DataRpcAsync dataService;
private final ConfigureDataView view;
public ConfigureDataPresenter(
Project project, DataRpcAsync rpcService,
ConfigureDataView view) {
this.project = project;
this.dataService = rpcService;
this.view = view;
refreshView();
}
@Override
public void refreshView() {
view.setPresenter(this);
dataService.getDataSources(
new TaCallback<List<DataSource>>("Getting data source options") {
@Override
public void onSuccess(List<DataSource> result) {
view.setDataSources(result);
}
});
dataService.getProjectRequests(project.getProjectId(),
new TaCallback<List<DataRequest>>("Getting data requests") {
@Override
public void onSuccess(List<DataRequest> result) {
view.setDataRequests(result);
}
});
}
@Override
public void addDataRequest(final DataRequest newRequest) {
newRequest.setParentProjectId(project.getProjectId());
dataService.addDataRequest(newRequest,
new TaCallback<Long>("Updating data request") {
@Override
public void onSuccess(Long result) {
newRequest.setRequestId(result);
refreshView();
}
});
}
@Override
public void updateDataRequest(DataRequest requestToUpdate) {
dataService.updateDataRequest(requestToUpdate, TaCallback.getNoopCallback());
}
@Override
public void deleteDataRequest(DataRequest requestToDelete) {
dataService.removeDataRequest(requestToDelete,
new TaCallback<Void>("Deleting data request") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
@Override
public Widget getView() {
return view.asWidget();
}
}
| 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.presenter;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.view.RiskView;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
/**
* Presenter for viewing a project's known risk, that is outstanding risk minus mitigations.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class KnownRiskPresenter extends RiskPresenter implements TaPagePresenter {
public KnownRiskPresenter(
Project project, ProjectRpcAsync projectService, RiskView view) {
super(project, projectService, view);
refreshView();
}
@Override
public void refreshView() {
refreshBaseView();
}
@Override
public Widget getView() {
return view.asWidget();
}
}
| 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.presenter;
import com.google.common.collect.Lists;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.client.event.ProjectElementAddedEvent;
import com.google.testing.testify.risk.frontend.client.event.ProjectHasNoElementsEvent;
import com.google.testing.testify.risk.frontend.client.view.AttributesView;
import com.google.testing.testify.risk.frontend.model.AccElementType;
import com.google.testing.testify.risk.frontend.model.AccLabel;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Project;
import com.google.testing.testify.risk.frontend.model.Signoff;
import com.google.testing.testify.risk.frontend.shared.rpc.DataRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
import java.util.Collection;
import java.util.List;
/**
* Presenter for the Attributes page.
*
* @author jimr@google.com (Jim Reardon)
*/
public class AttributesPresenter extends BasePagePresenter implements AttributesView.Presenter,
TaPagePresenter {
private final Project project;
private final ProjectRpcAsync projectService;
private final UserRpcAsync userService;
private final DataRpcAsync dataService;
private final AttributesView view;
private final EventBus eventBus;
private final Collection<String> projectLabels = Lists.newArrayList();
/**
* Constructs the Attributes page presenter.
*/
public AttributesPresenter(
Project project, ProjectRpcAsync projectService, UserRpcAsync userService,
DataRpcAsync dataService, AttributesView view, EventBus eventBus) {
this.project = project;
this.projectService = projectService;
this.userService = userService;
this.dataService = dataService;
this.view = view;
this.eventBus = eventBus;
refreshView();
}
/**
* Query the database for project information and populate UI fields.
*/
@Override
public void refreshView() {
view.setPresenter(this);
userService.hasEditAccess(project.getProjectId(),
new TaCallback<Boolean>("checking user access") {
@Override
public void onSuccess(Boolean result) {
if (result) {
view.enableEditing();
}
}
});
projectService.getProjectAttributes(project.getProjectId(),
new TaCallback<List<Attribute>>("loading attributes") {
@Override
public void onSuccess(List<Attribute> result) {
// If the project has no attributes, we need to broadcast it.
if (result.size() == 0) {
eventBus.fireEvent(
new ProjectHasNoElementsEvent(project, AccElementType.ATTRIBUTE));
}
view.setProjectAttributes(result);
}
});
projectService.getLabels(project.getProjectId(),
new TaCallback<List<AccLabel>>("loading labels") {
@Override
public void onSuccess(List<AccLabel> result) {
for (AccLabel l : result) {
projectLabels.add(l.getLabelText());
}
view.setProjectLabels(projectLabels);
}
});
dataService.getSignoffsByType(project.getProjectId(), AccElementType.ATTRIBUTE,
new TaCallback<List<Signoff>>("loading signoff details") {
@Override
public void onSuccess(List<Signoff> results) {
view.setSignoffs(results);
}
});
}
/** Returns the underlying view. */
@Override
public Widget getView() {
return view.asWidget();
}
@Override
public long getProjectId() {
return project.getProjectId();
}
/**
* Adds a new Attribute to the data store.
*/
@Override
public void createAttribute(final Attribute attribute) {
projectService.createAttribute(attribute,
new TaCallback<Long>("creating attribute") {
@Override
public void onSuccess(Long result) {
attribute.setAttributeId(result);
eventBus.fireEvent(new ProjectElementAddedEvent(attribute));
refreshView();
}
});
}
/**
* Updates the given attribute in the database.
*/
@Override
public void updateAttribute(Attribute attributeToUpdate) {
projectService.updateAttribute(attributeToUpdate,
new TaCallback<Attribute>("updating attribute") {
@Override
public void onSuccess(Attribute result) {
view.refreshAttribute(result);
}
});
}
@Override
public void updateSignoff(Attribute attribute, boolean newSignoff) {
dataService.setSignedOff(attribute.getParentProjectId(), AccElementType.ATTRIBUTE,
attribute.getAttributeId(), newSignoff, TaCallback.getNoopCallback());
}
/**
* Removes the given attribute from the Project.
*/
@Override
public void removeAttribute(Attribute attributeToRemove) {
projectService.removeAttribute(attributeToRemove,
new TaCallback<Void>("deleting attribute") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
@Override
public void reorderAttributes(List<Long> newOrder) {
projectService.reorderAttributes(
project.getProjectId(), newOrder,
new TaCallback<Void>("reordering attributes") {
@Override
public void onSuccess(Void result) {
refreshView();
}
});
}
@Override
public ProjectRpcAsync getProjectService() {
return projectService;
}
}
| 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.List;
/**
* View on top of any user interface for visualizing a project's Risk or Risk Mitigations.
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface RiskView {
/**
* Initializes user interface elements with the given components.
*/
public void setComponents(List<Component> components);
/**
* Initializes user interface elements with the given attributes.
*/
public void setAttributes(List<Attribute> attributes);
/**
* Notifies the view of all Project Components.
*/
public void setCapabilities(List<Capability> capabilities);
/**
* Converts the view into a GWT widget.
*/
public Widget asWidget();
}
| 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.client.presenter.TaPagePresenter;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Bug;
import com.google.testing.testify.risk.frontend.model.Capability;
import com.google.testing.testify.risk.frontend.model.Checkin;
import com.google.testing.testify.risk.frontend.model.Component;
import com.google.testing.testify.risk.frontend.model.TestCase;
import java.util.Collection;
import java.util.List;
/**
* View on top of the CapabilityDetails page.
*
* @author jimr@google.com (Jim Reardon)
*/
public interface CapabilityDetailsView {
/**
* Presenter interface for this view.
*/
public interface Presenter extends TaPagePresenter {
public void assignBugToCapability(long capabilityId, long bugId);
public void assignCheckinToCapability(long capabilityId, long checkinId);
public void assignTestCaseToCapability(long capabilityId, long testId);
public void updateCapability(Capability capability);
public void setSignoff(long capabilityId, boolean isSignedOff);
}
public void setAttributes(List<Attribute> attributes);
public void setBugs(List<Bug> bugs);
public void setComponents(List<Component> components);
public void setCapability(Capability capability);
public void setTests(List<TestCase> tests);
public void setCheckins(List<Checkin> checkins);
public void setSignoff(boolean signoff);
public void setProjectLabels(Collection<String> labels);
public void setPresenter(Presenter presenter);
/**
* Reset clears all stored data. Call before refresh, or setting new data,
* to avoid staggering updates. */
public void reset();
public void makeEditable();
public void refresh();
public Widget asWidget();
}
| 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.Signoff;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import java.util.Collection;
import java.util.List;
/**
* View on top of the ProjectAttributes page.
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface AttributesView {
/**
* Interface for notifying the Presenter about events arising from the View.
*/
public interface Presenter {
/**
* @return the ProjectID for the project the View is displaying.
*/
long getProjectId();
/**
* Notifies the Presenter that a new Attribute has been created.
*/
public void createAttribute(Attribute attribute);
/**
* Updates the given Attribute in the database.
*/
public void updateAttribute(Attribute attributeToUpdate);
public void updateSignoff(Attribute attribute, boolean newSignoff);
/**
* Removes the given Attribute from the Project.
*/
public void removeAttribute(Attribute attributeToRemove);
/**
* Reorders the project's list of Attributes.
*/
public void reorderAttributes(List<Long> newOrder);
/** Get the ProjectService associated with the presenter. */
public ProjectRpcAsync getProjectService();
}
/**
* Bind the view and the underlying presenter it communicates with.
*/
public void setPresenter(Presenter presenter);
/**
* Initialize user interface elements with the given set of Attributes.
*/
public void setProjectAttributes(List<Attribute> attributes);
/** Update a single attribute */
public void refreshAttribute(Attribute attribute);
/** All of this project's labels. Used for autocomplete drop-down. */
public void setProjectLabels(Collection<String> projectLabels);
/**
* Data on which elements have been signed off.
*/
public void setSignoffs(List<Signoff> signoffs);
/**
* Updates the view to enable editing of attribute data.
*/
public void enableEditing();
/**
* Converts the view into a GWT widget.
*/
public Widget asWidget();
}
| 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.AccLabel;
import com.google.testing.testify.risk.frontend.model.Component;
import java.util.List;
/**
* View for a Component widget.
* {@See com.google.testing.testify.risk.frontend.model.Component}
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface ComponentView {
/**
* Interface for notifying the Presenter about events arising from the View.
*/
public interface Presenter {
/**
* Returns the project ID of the target Component.
*/
public long getProjectId();
/**
* Returns the Component ID of the target Component.
*/
public long getComponentId();
public void updateSignoff(boolean newSignoff);
public void onDescriptionEdited(String description);
/**
* Called when the user renames the given component.
*/
public void onRename(String newComponentName);
/**
* Called when the user deletes the given Component.
*/
public void onRemove();
/**
* Called when the user updates a label.
*/
public void onUpdateLabel(AccLabel label, String newText);
/**
* Called when the user adds a new Label.
*/
public void onAddLabel(String label);
/**
* Called when the user removes a label.
*/
public void onRemoveLabel(AccLabel label);
public void refreshView(Component component);
/** Requests the presenter refresh the view's controls. */
public void refreshView();
}
/**
* Bind the view and the underlying presenter it communicates with.
*/
public void setPresenter(Presenter presenter);
/**
* Set the UI to display the Component's name.
*/
public void setComponentName(String componentName);
public void setDescription(String description);
public void setSignedOff(boolean signedOff);
/**
* Set the UI to display the Component's ID.
*/
public void setComponentId(Long componentId);
/**
* Set the UI to display the given Component labels.
*/
public void setComponentLabels(List<AccLabel> componentLabels);
/**
* Updates the view to enable editing of attribute data.
*/
public void enableEditing();
/**
* Hides the Widget so it is no longer visible. (Typically after the Component has been deleted.)
*/
public void hide();
/**
* Converts the view into a GWT widget.
*/
public Widget asWidget();
}
| 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.Project;
import com.google.testing.testify.risk.frontend.shared.rpc.ProjectRpcAsync;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc.ProjectAccess;
import java.util.List;
/**
* View on top of the ProjectSettings Widget.
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface ProjectSettingsView {
/**
* Interface for notifying the Presenter about events arising from the View.
*/
public interface Presenter {
/**
* @return the ProjectID for the project the View is displaying.
*/
long getProjectId();
/**
* @return a handle to the Presenter's ProjectService serverlet. Ideally this should be hidden.
*/
ProjectRpcAsync getProjectService();
/**
* Updates the project name, summary, and description get updated in one batch action.
*/
void onUpdateProjectInfoClicked(
String projectName, String projectDescription,
List<String> projectOwners, List<String> projectEditors, List<String> projectViewers,
boolean isPublicalyVisible);
/**
* Deletes the Project. Proceed with caution.
*/
public void removeProject();
}
/**
* Shows the "project saved" panel.
*/
public void showSaved();
/**
* Updates the view to enable editing of project data. (Security will still be checked in the
* backend servlet.)
*/
public void enableProjectEditing(ProjectAccess userAccessLevel);
/**
* Bind the view and the underlying presenter it communicates with.
*/
public void setPresenter(Presenter presenter);
/**
* Initialize user interface elements with the given project settings.
*/
public void setProjectSettings(Project projectSettings);
/**
* Converts the view into a GWT widget.
*/
public Widget asWidget();
}
| 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.FilterOption;
import java.util.List;
import java.util.Map;
/**
* View for a Filter.
*
* @author jimr@google.com (Jim Reardon)
*/
public interface FilterView {
/** Interface for notifying the presenter about changes to this view. */
public interface Presenter {
/** Called when the options for this filter are updated. */
public void onUpdate(List<FilterOption> newOptions, String conjunction, Long attribute,
Long component, Long capability);
/** Called when this filter is deleted. */
public void onRemove();
/** Called to refresh the view. */
public void refreshView();
}
/** Binds the view to the presenter. */
public void setPresenter(Presenter presenter);
/** Set the title to display for this filter. */
public void setFilterTitle(String title);
/** Set the available options for this filter. */
public void setFilterOptionChoices(List<String> filterOptionChoices);
/** Set the list of current configuration of this filter: current options filtered on and
* to what things are filtered.. */
public void setFilterSettings(List<FilterOption> options, String conjunction, Long attribute,
Long component, Long capability);
/** Set current list of ACC parts. */
public void setAttributes(Map<String, Long> attributes);
public void setComponents(Map<String, Long> components);
public void setCapabilities(Map<String, Long> capabilities);
/** Makes the widget invisible. */
public void hide();
/** View as a GWT widget. */
public Widget asWidget();
}
| 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.AccLabel;
import com.google.testing.testify.risk.frontend.model.Attribute;
import java.util.List;
/**
* View for an Attribute widget.
* {@See com.google.testing.testify.risk.frontend.model.Attribute}
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface AttributeView {
/**
* Interface for notifying the Presenter about events arising from the View.
*/
public interface Presenter {
/**
* Returns the project ID of the target Component.
*/
public long getProjectId();
/**
* Returns the Attribute ID of the target Attribute.
*/
public long getAttributeId();
public void updateSignoff(boolean newSignoff);
public void onDescriptionEdited(String description);
/**
* Called when the user renames the given Attribute.
*/
public void onRename(String newAttributeName);
/**
* Called when the user deletes the given Attribute.
*/
public void onRemove();
/**
* Called when the user adds a new Label.
*/
public void onAddLabel(String label);
/**
* Called when the user updates a Label.
*/
public void onUpdateLabel(AccLabel label, String newText);
/**
* Called when the user removes a label.
*/
public void onRemoveLabel(AccLabel label);
/** Updates the view with new attribute data. */
public void refreshView(Attribute attribute);
/** Requests the presenter refresh the view's controls. */
public void refreshView();
}
/**
* Bind the view and the underlying presenter it communicates with.
*/
public void setPresenter(Presenter presenter);
public void setDescription(String description);
public void setSignedOff(boolean signedOff);
/**
* Set the UI displaying the Attribute's name.
*/
public void setAttributeName(String name);
/**
* Set the UI displaying the Attribute's ID.
*/
public void setAttributeId(Long id);
/**
* Set the UI to display the given labels.
*/
public void setLabels(List<AccLabel> labels);
/**
* Updates the view to enable editing of attribute data.
*/
public void enableEditing();
/**
* Hides the Widget so it is no longer visible. (Typically after the Attribute has been deleted.)
*/
public void hide();
/**
* Converts the view into a GWT widget.
*/
public Widget asWidget();
}
| 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.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import java.util.Iterator;
/**
* Customized VerticalPanel for a page. The following CSS classes are exposed by this
* widget:
*
* tty-PageSectionVerticalPanel - The entire panel.
* tty-PageSectionVerticalPanelHeader - The header text.
* tty-PageSectionVerticalPanelItem - Each item in the panel.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class PageSectionVerticalPanel extends Composite implements HasWidgets {
private final Label header = new Label();
private final VerticalPanel content = new VerticalPanel();
public PageSectionVerticalPanel() {
header.addStyleName("tty-PageSectionVerticalPanelHeader");
content.addStyleName("tty-PageSectionVerticalPanel");
content.add(header);
this.initWidget(content);
}
public void setHeaderText(String newTitle) {
header.setText(newTitle);
}
@Override
public void add(Widget w) {
w.addStyleName("tty-PageSectionVerticalPanelItem");
content.add(w);
}
@Override
public void clear() {
content.clear();
content.add(header);
}
@Override
public Iterator<Widget> iterator() {
return content.iterator();
}
@Override
public boolean remove(Widget w) {
return content.remove(w);
}
}
| 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.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import java.util.Iterator;
/**
* Organization unit for a navigation pane.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class NavSectionPanel extends Composite implements HasWidgets {
/** Used to wire parent class to associated UI Binder. */
interface NavSectionPanelUiBinder extends UiBinder<Widget, NavSectionPanel> {}
private static final NavSectionPanelUiBinder uiBinder = GWT.create(NavSectionPanelUiBinder.class);
@UiField
public Label sectionTitle;
@UiField
public VerticalPanel content;
public NavSectionPanel() {
initWidget(uiBinder.createAndBindUi(this));
}
public String getSectionTitle() {
return sectionTitle.getText();
}
public void setSectionTitle(String newTitle) {
sectionTitle.setText(newTitle);
}
@Override
public void add(Widget w) {
content.add(w);
}
@Override
public void clear() {
content.clear();
}
@Override
public Iterator<Widget> iterator() {
return content.iterator();
}
@Override
public boolean remove(Widget w) {
return content.remove(w);
}
}
| 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.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLTable.CellFormatter;
import com.google.gwt.user.client.ui.Label;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Capability;
import com.google.testing.testify.risk.frontend.model.Component;
import com.google.testing.testify.risk.frontend.model.Pair;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* A widget for displaying a set of capabilities in a Grid.
*
* @author jimr@google.com (Jim Reardon)
*/
public class CapabilitiesGridWidget extends Composite
implements HasValueChangeHandlers<Pair<Component, Attribute>> {
private final List<Attribute> attributes = Lists.newArrayList();
private final List<Component> components = Lists.newArrayList();
// Map from intersection key to capability list.
private final Multimap<Integer, Capability> capabilityMap = HashMultimap.create();
// Map from intersection key to table cell.
private final Map<Integer, HTML> cellMap = Maps.newHashMap();
private final Grid grid = new Grid();
private int highlightedCellRow = -1;
private int highlightedCellColumn = -1;
public CapabilitiesGridWidget() {
grid.addStyleName("tty-ComponentAttributeGrid");
grid.addStyleName("tty-CapabilitiesGrid");
initWidget(grid);
}
/**
* Adds a single capability without clearing out prior capabilities.
*
* @param capability capability to add.
*/
public void addCapability(Capability capability) {
Integer key = capability.getCapabilityIntersectionKey();
// Add the capability.
addCapabilityWithoutUpdate(capability);
// Update relevant UI field.
updateGridCell(key);
}
public void deleteCapability(Capability capability) {
for (Integer key : capabilityMap.keySet()) {
Collection<Capability> c = capabilityMap.get(key);
if (c.contains(capability)) {
c.remove(capability);
updateGridCell(key);
}
}
}
public void updateCapability(Capability capability) {
deleteCapability(capability);
addCapability(capability);
}
public void setAttributes(List<Attribute> attributes) {
this.attributes.clear();
this.attributes.addAll(attributes);
redrawGrid();
}
public void setComponents(List<Component> components) {
this.components.clear();
this.components.addAll(components);
redrawGrid();
}
public void setCapabilities(List<Capability> capabilities) {
capabilityMap.clear();
for (Capability capability : capabilities) {
addCapabilityWithoutUpdate(capability);
}
updateGridCells();
}
private void addCapabilityWithoutUpdate(Capability capability) {
Integer key = capability.getCapabilityIntersectionKey();
capabilityMap.put(key, capability);
}
/**
* Completely recreates the grid then calls updateGridCells() to update contents of grid.
* This should be called if the list of components or attributes changes.
*/
private void redrawGrid() {
grid.clear();
cellMap.clear();
if (components.size() < 1 || attributes.size() < 1) {
return;
}
grid.resize(components.size() + 1, attributes.size() + 1);
grid.getCellFormatter().setStyleName(0, 0, "tty-GridXHeaderCell");
// Add component headers.
for (int i = 0; i < components.size(); i++) {
Label label = new Label(components.get(i).getName());
grid.getCellFormatter().setStyleName(i + 1, 0, "tty-GridXHeaderCell");
grid.setWidget(i + 1, 0, label);
}
// Add attribute headers.
for (int i = 0; i < attributes.size(); i++) {
Label label = new Label(attributes.get(i).getName());
grid.getCellFormatter().setStyleName(0, i + 1, "tty-GridYHeaderCell");
grid.setWidget(0, i + 1, label);
}
// Fill up the rest of the grid with labels.
for (int cIndex = 0; cIndex < components.size(); cIndex++) {
for (int aIndex = 0; aIndex < attributes.size(); aIndex++) {
int row = cIndex + 1;
int column = aIndex + 1;
Component component = components.get(cIndex);
Attribute attribute = attributes.get(aIndex);
Integer key = Capability.getCapabilityIntersectionKey(component, attribute);
grid.getCellFormatter().setStyleName(row, column, "tty-GridCell");
if (row == highlightedCellRow && column == highlightedCellColumn) {
grid.getCellFormatter().addStyleName(row, column, "tty-GridCellSelected");
}
HTML cell = new HTML();
cell.addClickHandler(cellClickHandler(row, column));
cell.addMouseOverHandler(createMouseOverHandler(row, column));
cell.addMouseOutHandler(createMouseOutHandler(row, column));
cellMap.put(key, cell);
grid.setWidget(row, column, cell);
}
}
updateGridCells();
}
/**
* Creates a mouse over handler for a specific row and column.
*
* @param row the row number.
* @param column the column number.
* @return the mouse over handler.
*/
private MouseOverHandler createMouseOverHandler(final int row, final int column) {
return new MouseOverHandler() {
@Override
public void onMouseOver(MouseOverEvent event) {
mouseOver(row, column);
}
};
}
/**
* Generates a mouse out handler for a specific row and column.
*
* @param row the row.
* @param column the column.
* @return a mouse out handler.
*/
private MouseOutHandler createMouseOutHandler(final int row, final int column) {
return new MouseOutHandler() {
@Override
public void onMouseOut(MouseOutEvent event) {
mouseOut(row, column);
}
};
}
/**
* Handles a mouse out event by removing the formatting on cells that were once highlighted due
* to a mouse over event.
*
* @param row the row that lost mouse over.
* @param column the column that lost mouse over.
*/
private void mouseOut(int row, int column) {
CellFormatter formatter = grid.getCellFormatter();
// Remove highlighting from cell.
formatter.removeStyleName(row, column, "tty-GridCellHighlighted");
// Remove column highlighting.
for (int i = 1; i < grid.getRowCount(); i++) {
formatter.removeStyleName(i, column, "tty-GridColumnHighlighted");
}
// Remove row highlighting.
for (int j = 1; j < grid.getColumnCount(); j++) {
formatter.removeStyleName(row, j, "tty-GridRowHighlighted");
}
}
/**
* Handles a mouse over event by highlighting the moused over cell and adding style to the
* row and column that is also to be highlighted.
*
* @param row the row that gained mouse over.
* @param column the column that gained mouse over.
*/
private void mouseOver(int row, int column) {
CellFormatter formatter = grid.getCellFormatter();
// Add highlighting to cell.
formatter.addStyleName(row, column, "tty-GridCellHighlighted");
// Add column highlighting.
for (int i = 1; i < grid.getRowCount(); i++) {
if (i != row) {
formatter.addStyleName(i, column, "tty-GridColumnHighlighted");
}
}
// Add row highlighting.
for (int j = 1; j < grid.getColumnCount(); j++) {
if (j != column) {
formatter.addStyleName(row, j, "tty-GridRowHighlighted");
}
}
}
/**
* This updates the contents of the grid based off the current capability data.
*/
private void updateGridCells() {
for (Integer key : cellMap.keySet()) {
updateGridCell(key);
}
}
private void updateGridCell(Integer key) {
int size = capabilityMap.get(key).size();
String text = " ";
if (size > 0) {
text = Integer.toString(size);
}
cellMap.get(key).setHTML(text);
}
private ClickHandler cellClickHandler(final int row, final int column) {
final HasValueChangeHandlers<Pair<Component, Attribute>> self = this;
return new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
cellClicked(row, column);
}
};
}
private void cellClicked(int row, int column) {
final Component component = components.get(row - 1);
final Attribute attribute = attributes.get(column - 1);
if (highlightedCellRow != -1 && highlightedCellColumn != -1) {
grid.getCellFormatter().removeStyleName(
highlightedCellRow, highlightedCellColumn, "tty-GridCellSelected");
}
grid.getCellFormatter().addStyleName(row, column, "tty-GridCellSelected");
highlightedCellRow = row;
highlightedCellColumn = column;
ValueChangeEvent.fire(this, new Pair<Component, Attribute>(component, attribute));
}
@Override
public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<Pair<Component, Attribute>> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
}
| 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.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.testing.testify.risk.frontend.client.TaCallback;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpc;
import com.google.testing.testify.risk.frontend.shared.rpc.UserRpcAsync;
/**
* Project favorite star. Used to track user favorites. Note that the project favorite star defines
* the CSS style tty-ProjectFavoriteStar.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ProjectFavoriteStar extends Composite {
private final UserRpcAsync userService;
private boolean isStarred = false;
private final Image starImage = new Image();
private static final String STAR_ON_URL = "images/star-on.png";
private static final String STAR_OFF_URL = "images/star-off.png";
public ProjectFavoriteStar() {
userService = GWT.create(UserRpc.class);
starImage.setUrl(STAR_OFF_URL);
starImage.addStyleName("tty-ProjectFavoriteStar");
initWidget(starImage);
}
/** Set's the widget's Starred status. */
public void setStarredStatus(boolean isStarred) {
this.isStarred = isStarred;
if (isStarred) {
starImage.setUrl(STAR_ON_URL);
} else {
starImage.setUrl(STAR_OFF_URL);
}
}
/**
* Attach the current favorite star to the given Project ID. When this widget is clicked, it will
* make an RPC call to add the project as a favorite of the user.
*/
public void attachToProject(final long projectId) {
// Add 'click status'.
starImage.addClickHandler(
new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setStarredStatus(!isStarred);
if (isStarred) {
userService.starProject(projectId, TaCallback.getNoopCallback());
} else {
userService.unstarProject(projectId, TaCallback.getNoopCallback());
}
}
});
}
}
| 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.uibinder.client.UiFactory;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.model.Capability;
/**
* A widget that displays risk details to the user. No editing is done via this widget, just
* informational display.
*
* @author jimr@google.com (Jim Reardon)
*/
public class RiskCapabilityWidget extends BaseCapabilityWidget {
private final String risk;
private Label riskLabel;
public RiskCapabilityWidget(Capability capability, String risk) {
super(capability);
this.risk = risk;
updateRiskLabel();
}
@Override
public void makeEditable() {
// Always disable editing, no matter what. This is not a widget for editing, but for viewing.
}
private void updateRiskLabel() {
riskLabel.setText("Risk: " + risk);
}
@UiFactory @Override
public EasyDisclosurePanel createDisclosurePanel() {
HorizontalPanel header = new HorizontalPanel();
header.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
header.setStyleName("tty-CapabilityRiskHeader");
header.add(capabilityLabel);
riskLabel = new Label();
riskLabel.setStyleName("tty-CapabilityRiskValueHeader");
updateRiskLabel();
header.add(riskLabel);
EasyDisclosurePanel panel = new EasyDisclosurePanel(header);
panel.setOpen(false);
return panel;
}
public void setRiskContent(Widget content) {
disclosureContent.setWidget(content);
}
}
| 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.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.TextBox;
/**
* Widget for a DataRequest parameter with an arbitrary parameter key.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class CustomParameterWidget extends Composite implements DataRequestParameterWidget {
private final TextBox keyTextBox = new TextBox();
private final TextBox valueTextBox = new TextBox();
private boolean isDeleted = false;
private final Image removeParameterImage = new Image("/images/x.png");
public CustomParameterWidget(String key, String value) {
HorizontalPanel panel = new HorizontalPanel();
panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
panel.addStyleName("tty-DataRequestParameter");
panel.add(keyTextBox);
panel.add(valueTextBox);
panel.add(removeParameterImage);
removeParameterImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent arg0) {
isDeleted = true;
fireChangeEvent();
}
});
initWidget(panel);
}
private void fireChangeEvent() {
NativeEvent event = Document.get().createChangeEvent();
ChangeEvent.fireNativeEvent(event, this);
}
@Override
public String getParameterKey() {
if (isDeleted) {
return null;
}
return keyTextBox.getText();
}
@Override
public String getParameterValue() {
if (isDeleted) {
return null;
}
return valueTextBox.getText();
}
@Override
public HandlerRegistration addChangeHandler(ChangeHandler handler) {
return addHandler(handler, ChangeEvent.getType());
}
@Override
public boolean isDeleted() {
return isDeleted;
}
}
| 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.dom.client.HasChangeHandlers;
import com.google.gwt.user.client.ui.Widget;
/**
* Base interface visualizing a parameter to a data request.
*
* @author chrsmith@google.com (Chris Smith)
*/
public interface DataRequestParameterWidget extends HasChangeHandlers {
public String getParameterKey();
public String getParameterValue();
public Widget asWidget();
public boolean isDeleted();
}
| 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.collect.Lists;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.util.NotificationUtil;
import com.google.testing.testify.risk.frontend.model.AccLabel;
import com.google.testing.testify.risk.frontend.model.Attribute;
import com.google.testing.testify.risk.frontend.model.Capability;
import com.google.testing.testify.risk.frontend.model.Component;
import com.google.testing.testify.risk.frontend.model.FailureRate;
import com.google.testing.testify.risk.frontend.model.UserImpact;
import java.util.Collection;
import java.util.List;
/**
* A capability widget that allows you to edit the details of the capability. Hook up
* an update and delete listener to be notified of edits on this widget.
*
* @author jimr@google.com (Jim Reardon)
*/
public class EditCapabilityWidget extends Composite implements HasValue<Capability> {
interface EditCapabilityWidgetUiBinder extends UiBinder<Widget, EditCapabilityWidget> {}
private static final EditCapabilityWidgetUiBinder uiBinder =
GWT.create(EditCapabilityWidgetUiBinder.class);
private Capability capability;
private final List<Attribute> attributes = Lists.newArrayList();
private final List<Component> components = Lists.newArrayList();
@UiField
protected FlowPanel labelsPanel;
@UiField
protected HorizontalPanel failurePanel;
@UiField
protected HorizontalPanel impactPanel;
@UiField
protected ListBox attributeBox;
@UiField
protected ListBox componentBox;
@UiField
protected TextBox capabilityName;
@UiField
protected TextArea description;
@UiField
protected Label capabilityGripper;
@UiField
protected HorizontalPanel buttonPanel;
@UiField
public HorizontalPanel savedPanel;
@UiField
protected EasyDisclosurePanel disclosurePanel;
@UiField
protected Button cancelButton;
@UiField
protected Button saveButton;
@UiField
protected Image deleteImage;
@UiField
protected Label capabilityId;
private final Label capabilityLabel = new Label();
private LabelWidget addNewLabel;
private Collection<String> labelSuggestions = Lists.newArrayList();
private boolean isEditable = false;
private boolean isDeletable = true;
/**
* Creates a widget which exposes the ability to edit the widget.
*
* @param capability the capability for this widget.
*/
public EditCapabilityWidget(Capability capability) {
this.capability = capability;
initWidget(uiBinder.createAndBindUi(this));
capabilityLabel.setText(capability.getName());
description.getElement().setAttribute("placeholder", "Enter description of this capability...");
refresh();
}
public Widget getCapabilityGripper() {
return capabilityGripper;
}
public void expand() {
disclosurePanel.setOpen(true);
}
public void setAttributes(List<Attribute> attributes) {
this.attributes.clear();
this.attributes.addAll(attributes);
refresh();
}
public void setComponents(List<Component> components) {
this.components.clear();
this.components.addAll(components);
refresh();
}
public long getCapabilityId() {
return capability.getCapabilityId();
}
public void disableDelete() {
isDeletable = false;
deleteImage.setVisible(false);
}
@UiFactory
public EasyDisclosurePanel createDisclosurePanel() {
EasyDisclosurePanel panel = new EasyDisclosurePanel(capabilityLabel);
panel.setOpen(false);
return panel;
}
@UiHandler("deleteImage")
protected void handleDelete(ClickEvent event) {
setValue(null, true);
}
@UiHandler("cancelButton")
protected void handleCancel(ClickEvent event) {
refresh();
}
@UiHandler("saveButton")
public void handleSave(ClickEvent event) {
savedPanel.setVisible(false);
long selectedAttribute;
long selectedComponent;
try {
selectedAttribute =
Long.parseLong(attributeBox.getValue(attributeBox.getSelectedIndex()));
selectedComponent =
Long.parseLong(componentBox.getValue(componentBox.getSelectedIndex()));
} catch (NumberFormatException e) {
NotificationUtil.displayErrorMessage("Couldn't save capability. The attribute or"
+ " component ID was invalid.");
return;
}
// Handle updates.
capability.setName(capabilityName.getValue());
capability.setDescription(description.getValue());
capability.setFailureRate(
FailureRate.fromDescription(getSelectedOptionInPanel(failurePanel)));
capability.setUserImpact(
UserImpact.fromDescription(getSelectedOptionInPanel(impactPanel)));
capability.setAttributeId(selectedAttribute);
capability.setComponentId(selectedComponent);
if ((capability.getComponentId() != selectedComponent)
|| (capability.getAttributeId() != selectedAttribute)) {
Window.alert("The capability " + capability.getName() + " will disappear from the "
+ " currently visible list because you have changed its attribute or component.");
}
// Tell the world that we've updated this capability.
ValueChangeEvent.fire(this, capability);
}
public void showSaved() {
// Show saved message.
savedPanel.setVisible(true);
Timer timer = new Timer() {
@Override
public void run() {
savedPanel.setVisible(false);
}
};
// Make the saved text disappear after 10 seconds.
timer.schedule(5000);
}
/**
* Updates the label suggestions for all labels on this view.
*/
public void setLabelSuggestions(Collection<String> labelSuggestions) {
this.labelSuggestions.clear();
this.labelSuggestions.addAll(labelSuggestions);
for (Widget w : labelsPanel) {
if (w instanceof LabelWidget) {
LabelWidget l = (LabelWidget) w;
l.setLabelSuggestions(this.labelSuggestions);
}
}
}
private void refresh() {
capabilityLabel.setText(capability.getName());
capabilityName.setText(capability.getName());
createLabelsPanel();
description.setText(capability.getDescription());
createFailureBox();
createImpactBox();
createAttributeBox();
createComponentBox();
capabilityName.setEnabled(isEditable);
capabilityGripper.setVisible(isEditable);
description.setEnabled(isEditable);
enableOrDisableAllRadioButtons(failurePanel, isEditable);
enableOrDisableAllRadioButtons(impactPanel, isEditable);
attributeBox.setEnabled(isEditable);
componentBox.setEnabled(isEditable);
buttonPanel.setVisible(isEditable);
}
private void createLabelsPanel() {
labelsPanel.clear();
for (AccLabel label : capability.getAccLabels()) {
createLabel(label);
}
addBlankLabel();
}
private void createLabel(final AccLabel label) {
final LabelWidget widget = new LabelWidget(label.getLabelText());
widget.setLabelSuggestions(labelSuggestions);
widget.setEditable(isEditable);
widget.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
if (event.getValue() == null) {
labelsPanel.remove(widget);
capability.removeLabel(label);
} else {
label.setLabelText(event.getValue());
}
}
});
labelsPanel.add(widget);
}
private void addBlankLabel() {
final String newText = "new label";
addNewLabel = new LabelWidget(newText, true);
addNewLabel.setLabelSuggestions(labelSuggestions);
addNewLabel.setEditable(true);
addNewLabel.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
labelsPanel.remove(addNewLabel);
AccLabel label = capability.addLabel(event.getValue());
createLabel(label);
addBlankLabel();
}
});
addNewLabel.setVisible(isEditable);
labelsPanel.add(addNewLabel);
}
private void createFailureBox() {
failurePanel.clear();
RadioButton button;
for (FailureRate rate : FailureRate.values()) {
button = new RadioButton("failure" + capability.getCapabilityId().toString(),
rate.getDescription());
failurePanel.add(button);
if (rate.equals(capability.getFailureRate())) {
button.setValue(true);
}
}
}
private void createImpactBox() {
impactPanel.clear();
RadioButton button;
for (UserImpact impact : UserImpact.values()) {
button = new RadioButton("impact" + capability.getCapabilityId().toString(),
impact.getDescription());
impactPanel.add(button);
if (impact.equals(capability.getUserImpact())) {
button.setValue(true);
}
}
}
private void enableOrDisableAllRadioButtons(Panel panel, boolean enable) {
for (Widget w : panel) {
if (w instanceof RadioButton) {
RadioButton b = (RadioButton) w;
b.setEnabled(enable);
}
}
}
private String getSelectedOptionInPanel(Panel panel) {
for (Widget w : panel) {
if (w instanceof RadioButton) {
RadioButton b = (RadioButton) w;
if (b.getValue()) {
return b.getText();
}
}
}
return null;
}
private void createAttributeBox() {
attributeBox.clear();
int i = 0;
for (Attribute attribute : attributes) {
attributeBox.addItem(attribute.getName(), attribute.getAttributeId().toString());
if (attribute.getAttributeId() == capability.getAttributeId()) {
attributeBox.setSelectedIndex(i);
}
i++;
}
}
private void createComponentBox() {
componentBox.clear();
int i = 0;
for (Component component : components) {
componentBox.addItem(component.getName(), component.getComponentId().toString());
if (component.getComponentId() == capability.getComponentId()) {
componentBox.setSelectedIndex(i);
}
i++;
}
}
public void makeEditable() {
isEditable = true;
deleteImage.setVisible(isDeletable);
enableOrDisableAllRadioButtons(failurePanel, true);
enableOrDisableAllRadioButtons(impactPanel, true);
description.setEnabled(true);
attributeBox.setEnabled(true);
componentBox.setEnabled(true);
capabilityName.setEnabled(true);
capabilityGripper.setVisible(true);
buttonPanel.setVisible(true);
for (Widget widget : labelsPanel) {
LabelWidget label = (LabelWidget) widget;
label.setEditable(true);
}
addNewLabel.setVisible(true);
}
@Override
public Capability getValue() {
return capability;
}
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Capability> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
@Override
public void setValue(Capability capability) {
this.capability = capability;
}
@Override
public void setValue(Capability capability, boolean fireEvents) {
this.capability = capability;
if (fireEvents) {
ValueChangeEvent.fire(this, capability);
}
}
}
| 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.widgets;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.TaApplication;
import com.google.testing.testify.risk.frontend.model.Capability;
/**
* Displays a Capability which, upon click, takes a user to another page.
*
* @author jimr@google.com (Jim Reardon)
*/
public class LinkCapabilityWidget extends Composite {
interface CapabilityWidgetBinder extends UiBinder<Widget, LinkCapabilityWidget> { }
private static final CapabilityWidgetBinder uiBinder = GWT.create(CapabilityWidgetBinder.class);
@UiField
public Label capabilityId;
@UiField
public Label capabilityLabel;
private final Capability capability;
/**
* @param capability
*/
public LinkCapabilityWidget(Capability capability) {
initWidget(uiBinder.createAndBindUi(this));
this.capability = capability;
initializeWidget();
}
private void initializeWidget() {
capabilityLabel.setText(capability.getName());
capabilityId.setText(Long.toString(capability.getCapabilityId()));
capabilityLabel.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
History.newItem("/" + capability.getParentProjectId()
+ "/" + TaApplication.PAGE_HISTORY_TOKEN_CAPABILITY_DETAILS
+ "/" + capability.getCapabilityId());
}
});
}
} | 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.dom.client.Document;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.HasHandlers;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import java.util.List;
/**
* Widget a constrained DataRequest parameter, where the key values are fixed.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class ConstrainedParameterWidget extends Composite implements DataRequestParameterWidget {
private final ListBox keyListBox = new ListBox();
private final TextBox valueTextBox = new TextBox();
private boolean isDeleted = false;
private final Image removeParameterImage = new Image("/images/x.png");
public ConstrainedParameterWidget(List<String> keyValues, String key, String value) {
keyListBox.clear();
for (String keyValue : keyValues) {
keyListBox.addItem(keyValue);
}
int startingKeyIndex = -1;
if (keyValues.contains(key)) {
startingKeyIndex = keyValues.indexOf(key);
} else {
// Initialized with a key not in the key values? Likely a bug somewhere...
startingKeyIndex = 0;
}
keyListBox.setSelectedIndex(startingKeyIndex);
valueTextBox.setText(value);
final HasHandlers self = this;
removeParameterImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent arg0) {
isDeleted = true;
fireChangeEvent();
}
});
HorizontalPanel panel = new HorizontalPanel();
panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
panel.addStyleName("tty-DataRequestParameter");
panel.add(keyListBox);
panel.add(valueTextBox);
panel.add(removeParameterImage);
initWidget(panel);
}
private void fireChangeEvent() {
NativeEvent event = Document.get().createChangeEvent();
ChangeEvent.fireNativeEvent(event, this);
}
@Override
public String getParameterKey() {
if (isDeleted) {
return null;
}
int selectedIndex = keyListBox.getSelectedIndex();
return keyListBox.getItemText(selectedIndex);
}
@Override
public String getParameterValue() {
if (isDeleted) {
return null;
}
return valueTextBox.getText();
}
@Override
public boolean isDeleted() {
return isDeleted;
}
@Override
public HandlerRegistration addChangeHandler(ChangeHandler handler) {
return addHandler(handler, ChangeEvent.getType());
}
}
| 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.common.collect.Lists;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.event.HasWidgetsReorderedHandler;
import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedEvent;
import com.google.testing.testify.risk.frontend.client.event.WidgetsReorderedHandler;
import com.allen_sauer.gwt.dnd.client.DragEndEvent;
import com.allen_sauer.gwt.dnd.client.DragHandler;
import com.allen_sauer.gwt.dnd.client.DragStartEvent;
import com.allen_sauer.gwt.dnd.client.PickupDragController;
import com.allen_sauer.gwt.dnd.client.drop.VerticalPanelDropController;
import java.util.Iterator;
import java.util.List;
/**
* A VerticalPanel which supports reordering via drag and drop.
*
* @param <T> Type of the widget to display on the panel.
* @author chrsmith@google.com (Chris Smith)
*/
public class SortableVerticalPanel<T extends Widget> extends Composite
implements HasWidgetsReorderedHandler, Iterable<Widget> {
private final SimplePanel content = new SimplePanel();
private VerticalPanel currentVerticalPanel = new VerticalPanel();
public SortableVerticalPanel() {
initWidget(content);
}
/**
* Clears the vertical panel and adds the list of widgets. The provided function will be used to
* get the widget's drag target (such as header text or a gripper image).
*
* @param widgets the list of widgets to display on the generated panel.
* @param getDragTarget function for getting the 'dragable area' of any given widget. (Such as
* a gripping area or header label.
*/
public void setWidgets(List<T> widgets, Function<T, Widget> getDragTarget) {
AbsolutePanel boundaryPanel = new AbsolutePanel();
boundaryPanel.setSize("100%", "100%");
boundaryPanel.clear();
content.clear();
content.add(boundaryPanel);
// The VerticalPanel which actually holds the list of widgets.
currentVerticalPanel = new VerticalPanel();
// The VerticalPanelDropController handles DOM manipulation.
final VerticalPanelDropController widgetDropController =
new VerticalPanelDropController(currentVerticalPanel);
boundaryPanel.add(currentVerticalPanel);
DragHandler dragHandler = createDragHandler(currentVerticalPanel);
PickupDragController widgetDragController = new PickupDragController(boundaryPanel, false);
widgetDragController.setBehaviorMultipleSelection(false);
widgetDragController.addDragHandler(dragHandler);
widgetDragController.registerDropController(widgetDropController);
// Add each widget to the VerticalPanel and enable dragging via its DragTarget.
for (T widget : widgets) {
currentVerticalPanel.add(widget);
widgetDragController.makeDraggable(widget, getDragTarget.apply(widget));
}
}
/**
* Returns the number of Widgets on the VerticalPanel.
*/
public int getWidgetCount() {
return currentVerticalPanel.getWidgetCount();
}
/**
* Returns the Widget at the specified index.
*/
public Widget getWidget(int index) {
return currentVerticalPanel.getWidget(index);
}
/**
* Returns a generic DragHandler for notification of drag events.
*/
private DragHandler createDragHandler(final VerticalPanel verticalPanel) {
// TODO(chrsmith): Provide a way to hook into events. (Required to preserve ordering.)
return new DragHandler() {
@Override
public void onDragEnd(DragEndEvent event) {
List<Widget> widgetList = Lists.newArrayList();
for (int index = 0; index < verticalPanel.getWidgetCount(); index++) {
widgetList.add(verticalPanel.getWidget(index));
}
fireEvent(new WidgetsReorderedEvent(widgetList));
}
@Override
public void onDragStart(DragStartEvent event) {}
@Override
public void onPreviewDragEnd(DragEndEvent event) {}
@Override
public void onPreviewDragStart(DragStartEvent event) {}
};
}
@Override
public HandlerRegistration addWidgetsReorderedHandler(WidgetsReorderedHandler handler) {
return super.addHandler(handler, WidgetsReorderedEvent.getType());
}
@Override
public Iterator<Widget> iterator() {
return currentVerticalPanel.iterator();
}
}
| 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.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiFactory;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.model.Capability;
/**
* Base display for a capability. This widget is intended to be extended to supply content
* in the disclosure panel depending on view (for example, on the Capabilities page, the ability
* to edit capability details would be contained there. On a risk page, details on the risk
* assessment would be contained there. And so on).
*
* @author jimr@google.com (Jim Reardon)
*/
public class BaseCapabilityWidget extends Composite implements HasValueChangeHandlers<Capability> {
interface CapabilityWidgetBinder extends UiBinder<Widget, BaseCapabilityWidget> { }
private static final CapabilityWidgetBinder uiBinder = GWT.create(CapabilityWidgetBinder.class);
@UiField
public Image capabilityGripper;
@UiField
public EasyDisclosurePanel disclosurePanel;
@UiField
public SimplePanel disclosureContent;
@UiField
public Label capabilityId;
@UiField
public Image deleteCapabilityImage;
protected final Label capabilityLabel = new Label();
protected final Capability capability;
// If this widget allows editing.
protected boolean isEditable = false;
public BaseCapabilityWidget(Capability capability) {
initWidget(uiBinder.createAndBindUi(this));
this.capability = capability;
initializeWidget();
}
@UiFactory
public EasyDisclosurePanel createDisclosurePanel() {
EasyDisclosurePanel panel = new EasyDisclosurePanel(capabilityLabel);
panel.setOpen(false);
return panel;
}
private void initializeWidget() {
capabilityLabel.setStyleName("tty-CapabilityName");
deleteCapabilityImage.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
ValueChangeEvent.fire(BaseCapabilityWidget.this, null);
}
});
capabilityLabel.setText(capability.getName());
capabilityId.setText(Long.toString(capability.getCapabilityId()));
}
public void makeEditable() {
isEditable = true;
capabilityGripper.setVisible(true);
deleteCapabilityImage.setVisible(true);
}
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<Capability> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
}
| 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.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.MultiWordSuggestOracle;
import com.google.gwt.user.client.ui.SuggestBox;
import com.google.gwt.user.client.ui.SuggestBox.DefaultSuggestionDisplay;
import java.util.Collection;
/**
* Displays a label with a little delete X as well. You can click the X to delete the label.
*
* @author jimr@google.com (Jim Reardon)
*/
public class LabelWidget extends Composite implements HasValue<String>,
HasValueChangeHandlers<String> {
private HorizontalPanel contentPanel = new HorizontalPanel();
private Image image = new Image();
// The deck panel will have to entries -- the view mode, and the edit mode. DeckPanel will
// only make one visible at a time.
private DeckPanel deckPanel = new DeckPanel();
private MultiWordSuggestOracle oracle = new MultiWordSuggestOracle(" -");
private SuggestBox inputBox = new SuggestBox(oracle);
private Label label = new Label();
private static final int VIEW_MODE = 0;
private static final int EDIT_MODE = 1;
private boolean canEdit = false;
public LabelWidget(String text) {
this(text, false);
}
/**
* Constructs a label for a given object, allowing customized styling. The constructed
* label will use styles:
* tty-GenericLabel
* tty-GenericLabelRemoveLabelImage
* @param text the textual representation for this label.
* @param isAddWidget true if this is a "new label..." widget, false if not.
*/
public LabelWidget(String text, final boolean isAddWidget) {
DefaultSuggestionDisplay suggestionDisplay =
(DefaultSuggestionDisplay) inputBox.getSuggestionDisplay();
suggestionDisplay.setPopupStyleName("tty-SuggestBoxPopup");
contentPanel.addStyleName("tty-RemovableLabel");
if (isAddWidget) {
// Craft a little plus image.
image.setStyleName("tty-RemovableLabelAddImage");
image.setUrl("images/collapsed_12.png");
image.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
switchMode(EDIT_MODE);
}
});
contentPanel.add(image);
}
// Craft the view mode.
label.setText(text);
label.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent arg0) {
switchMode(EDIT_MODE);
}
});
deckPanel.add(label);
// Craft the edit mode.
if (!isAddWidget) {
inputBox.setText(text);
}
inputBox.getTextBox().addBlurHandler(new BlurHandler() {
@Override
public void onBlur(BlurEvent arg0) {
switchMode(VIEW_MODE);
}
});
inputBox.getTextBox().addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
switchMode(VIEW_MODE);
} else if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE) {
if (isAddWidget) {
inputBox.setText("");
} else {
inputBox.setText(label.getText());
}
switchMode(VIEW_MODE);
}
}
});
// Explicitly does not call switchMode to avoid logic inside that function that would think
// we have switched from edit mode to view mode.
deckPanel.showWidget(VIEW_MODE);
deckPanel.add(inputBox);
contentPanel.add(deckPanel);
if (!isAddWidget) {
// Craft the delete button.
image.setStyleName("tty-RemovableLabelDeleteImage");
image.setUrl("images/x.png");
image.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
setValue(null, true);
}
});
contentPanel.add(image);
}
// Set some alignments to make the widget pretty.
contentPanel.setCellVerticalAlignment(label, HasVerticalAlignment.ALIGN_MIDDLE);
contentPanel.setCellVerticalAlignment(image, HasVerticalAlignment.ALIGN_MIDDLE);
initWidget(contentPanel);
}
private void switchMode(int mode) {
// Just keep them in view mode if they can't edit this widget.
if (!canEdit) {
deckPanel.showWidget(VIEW_MODE);
return;
}
if (mode == VIEW_MODE) {
String text = inputBox.getText();
if (!text.equals(label.getText())) {
// Don't save an empty label.
if (!"".equals(text)) {
// We have updates to save.
setValue(inputBox.getText(), true);
}
}
}
int width = label.getOffsetWidth();
deckPanel.showWidget(mode);
if (mode == EDIT_MODE) {
inputBox.setWidth(String.valueOf(String.valueOf(width)) + "px");
inputBox.setFocus(true);
}
}
public void setEditable(boolean canEdit) {
this.canEdit = canEdit;
image.setVisible(canEdit);
}
/**
* Sets the list of suggestions for the autocomplete box.
* @param suggestions list of items to suggest off of.
*/
public void setLabelSuggestions(Collection<String> suggestions) {
oracle.clear();
oracle.addAll(suggestions);
}
@Override
public String getValue() {
return label.getText();
}
@Override
public void setValue(String value) {
setValue(value, false);
}
@Override
public void setValue(String value, boolean fireEvents) {
String old = label.getText();
label.setText(value);
inputBox.setText(value);
if (fireEvents) {
ValueChangeEvent.fireIfNotEqual(this, old, value);
}
}
/**
* Will fire when value of text changes or delete is clicked (the value will be null if deleted).
*/
@Override
public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
}
| 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.ClickEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedEvent.DialogResult;
import com.google.testing.testify.risk.frontend.client.event.DialogClosedHandler;
import com.google.testing.testify.risk.frontend.client.event.HasDialogClosedHandler;
/**
* Standard dialog box with OK/Cancel buttons.
*
* @author chrsmith@google.com (Chris Smith)
*/
public class StandardDialogBox extends Composite implements HasDialogClosedHandler {
interface StandardDialogBoxUiBinder extends UiBinder<Widget, StandardDialogBox> {}
private static final StandardDialogBoxUiBinder uiBinder =
GWT.create(StandardDialogBoxUiBinder.class);
@UiField
protected VerticalPanel dialogContent;
@UiField
protected Button okButton;
@UiField
protected Button cancelButton;
/** If this is displayed, get a handle to the owning dialog box. */
private DialogBox dialogBox;
public StandardDialogBox() {
initWidget(uiBinder.createAndBindUi(this));
}
/**
* @return the dialog's content. Consumers will add any custom widgets to the returned Panel.
*/
public Panel getDialogContent() {
return dialogContent;
}
/**
* Displays the Dialog.
*/
public static void showAsDialog(StandardDialogBox dialogWidget) {
DialogBox dialogBox = new DialogBox();
dialogWidget.dialogBox = dialogBox;
dialogBox.addStyleName("tty-StandardDialogBox");
dialogBox.setText(dialogWidget.getTitle());
dialogBox.add(dialogWidget);
dialogBox.center();
dialogBox.show();
}
/**
* Gets called whenever the OK Button is clicked.
*/
@UiHandler("okButton")
public void handleOkButtonClicked(ClickEvent event) {
if (dialogBox != null) {
dialogBox.hide();
}
fireEvent(new DialogClosedEvent(DialogResult.OK));
}
/**
* Gets called whenever the Cancel Button is clicked.
*/
@UiHandler("cancelButton")
public void handleCancelButtonClicked(ClickEvent event) {
if (dialogBox != null) {
dialogBox.hide();
}
fireEvent(new DialogClosedEvent(DialogResult.Cancel));
}
@Override
public HandlerRegistration addDialogClosedHandler(DialogClosedHandler handler) {
return super.addHandler(handler, DialogClosedEvent.getType());
}
public void add(Widget w) {
dialogContent.add(w);
}
}
| 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.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(" ");
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.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(StringUtil.listToCsv(difference));
}
difference = StringUtil.subtractList(currentOwners, newOwners);
if (difference.size() > 0) {
warning.append("<br><br><b>Removed owners:</b> ");
warning.append(StringUtil.listToCsv(difference));
}
difference = StringUtil.subtractList(newEditors, currentEditors);
if (difference.size() > 0) {
warning.append("<br><br><b>Added editors:</b> ");
warning.append(StringUtil.listToCsv(difference));
}
difference = StringUtil.subtractList(currentEditors, newEditors);
if (difference.size() > 0) {
warning.append("<br><br><b>Removed editors:</b> ");
warning.append(StringUtil.listToCsv(difference));
}
difference = StringUtil.subtractList(newViewers, currentViewers);
if (difference.size() > 0) {
warning.append("<br><br><b>Added viewers:</b> ");
warning.append(StringUtil.listToCsv(difference));
}
difference = StringUtil.subtractList(currentViewers, newViewers);
if (difference.size() > 0) {
warning.append("<br><br><b>Removed viewers:</b> ");
warning.append(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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.