code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/**
* PhotoSorterActivity.java
*
* (c) Luke Hutchison (luke.hutch@mit.edu)
*
* --
*
* Released under the MIT license (but please notify me if you use this code, so that I can give your project credit at
* http://code.google.com/p/android-multitouch-controller ).
*
* MIT license: http://www.opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package org.metalev.multitouch.photosortr;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
public class PhotoSortrActivity extends Activity {
PhotoSortrView photoSorter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setTitle(R.string.instructions);
photoSorter = new PhotoSortrView(this);
setContentView(photoSorter);
}
@Override
protected void onResume() {
super.onResume();
photoSorter.loadImages(this);
}
@Override
protected void onPause() {
super.onPause();
photoSorter.unloadImages();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
photoSorter.trackballClicked();
return true;
}
return super.onKeyDown(keyCode, event);
}
} | Java |
package org.metalev.multitouch.controller;
/**
* MultiTouchController.java
*
* Author: Luke Hutchison (luke.hutch@mit.edu)
* Please drop me an email if you use this code so I can list your project here!
*
* Usage:
* <code>
* public class MyMTView extends View implements MultiTouchObjectCanvas<PinchWidgetType> {
*
* private MultiTouchController<PinchWidgetType> multiTouchController = new MultiTouchController<PinchWidgetType>(this);
*
* // Pass touch events to the MT controller
* public boolean onTouchEvent(MotionEvent event) {
* return multiTouchController.onTouchEvent(event);
* }
*
* // ... then implement the MultiTouchObjectCanvas interface here, see details in the comments of that interface.
* }
* </code>
*
* Changelog:
* 2010-06-09 v1.5.1 Some API changes to make it possible to selectively update or not update scale / rotation.
* Fixed anisotropic zoom. Cleaned up rotation code. Added more comments. Better var names. (LH)
* 2010-06-09 v1.4 Added ability to track pinch rotation (Mickael Despesse, author of "Face Frenzy") and anisotropic pinch-zoom (LH)
* 2010-06-09 v1.3.3 Bugfixes for Android-2.1; added optional debug info (LH)
* 2010-06-09 v1.3 Ported to Android-2.2 (handle ACTION_POINTER_* actions); fixed several bugs; refactoring; documentation (LH)
* 2010-05-17 v1.2.1 Dual-licensed under Apache and GPL licenses
* 2010-02-18 v1.2 Support for compilation under Android 1.5/1.6 using introspection (mmin, author of handyCalc)
* 2010-01-08 v1.1.1 Bugfixes to Cyanogen's patch that only showed up in more complex uses of controller (LH)
* 2010-01-06 v1.1 Modified for official level 5 MT API (Cyanogen)
* 2009-01-25 v1.0 Original MT controller, released for hacked G1 kernel (LH)
*
* TODO:
* - Add inertia (flick-pinch-zoom or flick-scroll)
* - Merge in Paul Bourke's "grab" support for single-finger drag of objects: git://github.com/brk3/android-multitouch-controller.git
* (Initial concern are the two lines of the form "newScale = mCurrXform.scale - 0.04f", and the line in pastThreshold() that says
* "if (newScale == mCurrXform.scale)" -- this doesn't look like a robust solution to convey state, by changing scale by a tiny
* amount, but maybe I'm not understanding the intent behind the code or its behavior).
*
* Known usages: see http://code.google.com/p/android-multitouch-controller/
*
* --
*
* Released under the MIT license (but please notify me if you use this code, so that I can give your project credit at
* http://code.google.com/p/android-multitouch-controller ).
*
* MIT license: http://www.opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import java.lang.reflect.Method;
import android.util.Log;
import android.view.MotionEvent;
/**
* A class that simplifies the implementation of multitouch in applications. Subclass this and read the fields here as needed in subclasses.
*
* @author Luke Hutchison
*/
public class MultiTouchController<T> {
/**
* Time in ms required after a change in event status (e.g. putting down or lifting off the second finger) before events actually do anything --
* helps eliminate noisy jumps that happen on change of status
*/
private static final long EVENT_SETTLE_TIME_INTERVAL = 20;
/**
* The biggest possible abs val of the change in x or y between multitouch events (larger dx/dy events are ignored) -- helps eliminate jumps in
* pointer position on finger 2 up/down.
*/
private static final float MAX_MULTITOUCH_POS_JUMP_SIZE = 30.0f;
/**
* The biggest possible abs val of the change in multitouchWidth or multitouchHeight between multitouch events (larger-jump events are ignored) --
* helps eliminate jumps in pointer position on finger 2 up/down.
*/
private static final float MAX_MULTITOUCH_DIM_JUMP_SIZE = 40.0f;
/** The smallest possible distance between multitouch points (used to avoid div-by-zero errors and display glitches) */
private static final float MIN_MULTITOUCH_SEPARATION = 30.0f;
/** The max number of touch points that can be present on the screen at once */
public static final int MAX_TOUCH_POINTS = 20;
/** Generate tons of log entries for debugging */
public static final boolean DEBUG = false;
// ----------------------------------------------------------------------------------------------------------------------
MultiTouchObjectCanvas<T> objectCanvas;
/** The current touch point */
private PointInfo mCurrPt;
/** The previous touch point */
private PointInfo mPrevPt;
/** Fields extracted from mCurrPt */
private float mCurrPtX, mCurrPtY, mCurrPtDiam, mCurrPtWidth, mCurrPtHeight, mCurrPtAng;
/**
* Extract fields from mCurrPt, respecting the update* fields of mCurrPt. This just avoids code duplication. I hate that Java doesn't support
* higher-order functions, tuples or multiple return values from functions.
*/
private void extractCurrPtInfo() {
// Get new drag/pinch params. Only read multitouch fields that are needed,
// to avoid unnecessary computation (diameter and angle are expensive operations).
mCurrPtX = mCurrPt.getX();
mCurrPtY = mCurrPt.getY();
mCurrPtDiam = Math.max(MIN_MULTITOUCH_SEPARATION * .71f, !mCurrXform.updateScale ? 0.0f : mCurrPt.getMultiTouchDiameter());
mCurrPtWidth = Math.max(MIN_MULTITOUCH_SEPARATION, !mCurrXform.updateScaleXY ? 0.0f : mCurrPt.getMultiTouchWidth());
mCurrPtHeight = Math.max(MIN_MULTITOUCH_SEPARATION, !mCurrXform.updateScaleXY ? 0.0f : mCurrPt.getMultiTouchHeight());
mCurrPtAng = !mCurrXform.updateAngle ? 0.0f : mCurrPt.getMultiTouchAngle();
}
// ----------------------------------------------------------------------------------------------------------------------
/** Whether to handle single-touch events/drags before multi-touch is initiated or not; if not, they are handled by subclasses */
private boolean handleSingleTouchEvents;
/** The object being dragged/stretched */
private T selectedObject = null;
/** Current position and scale of the dragged object */
private PositionAndScale mCurrXform = new PositionAndScale();
/** Drag/pinch start time and time to ignore spurious events until (to smooth over event noise) */
private long mSettleStartTime, mSettleEndTime;
/** Conversion from object coords to screen coords */
private float startPosX, startPosY;
/** Conversion between scale and width, and object angle and start pinch angle */
private float startScaleOverPinchDiam, startAngleMinusPinchAngle;
/** Conversion between X scale and width, and Y scale and height */
private float startScaleXOverPinchWidth, startScaleYOverPinchHeight;
// ----------------------------------------------------------------------------------------------------------------------
/** No touch points down. */
private static final int MODE_NOTHING = 0;
/** One touch point down, dragging an object. */
private static final int MODE_DRAG = 1;
/** Two or more touch points down, stretching/rotating an object using the first two touch points. */
private static final int MODE_PINCH = 2;
/** Current drag mode */
private int mMode = MODE_NOTHING;
// ----------------------------------------------------------------------------------------------------------------------
/** Constructor that sets handleSingleTouchEvents to true */
public MultiTouchController(MultiTouchObjectCanvas<T> objectCanvas) {
this(objectCanvas, true);
}
/** Full constructor */
public MultiTouchController(MultiTouchObjectCanvas<T> objectCanvas, boolean handleSingleTouchEvents) {
this.mCurrPt = new PointInfo();
this.mPrevPt = new PointInfo();
this.handleSingleTouchEvents = handleSingleTouchEvents;
this.objectCanvas = objectCanvas;
}
// ------------------------------------------------------------------------------------
/**
* Whether to handle single-touch events/drags before multi-touch is initiated or not; if not, they are handled by subclasses. Default: true
*/
protected void setHandleSingleTouchEvents(boolean handleSingleTouchEvents) {
this.handleSingleTouchEvents = handleSingleTouchEvents;
}
/**
* Whether to handle single-touch events/drags before multi-touch is initiated or not; if not, they are handled by subclasses. Default: true
*/
protected boolean getHandleSingleTouchEvents() {
return handleSingleTouchEvents;
}
// ------------------------------------------------------------------------------------
public static final boolean multiTouchSupported;
private static Method m_getPointerCount;
private static Method m_getPointerId;
private static Method m_getPressure;
private static Method m_getHistoricalX;
private static Method m_getHistoricalY;
private static Method m_getHistoricalPressure;
private static Method m_getX;
private static Method m_getY;
private static int ACTION_POINTER_UP = 6;
private static int ACTION_POINTER_INDEX_SHIFT = 8;
static {
boolean succeeded = false;
try {
// Android 2.0.1 stuff:
m_getPointerCount = MotionEvent.class.getMethod("getPointerCount");
m_getPointerId = MotionEvent.class.getMethod("getPointerId", Integer.TYPE);
m_getPressure = MotionEvent.class.getMethod("getPressure", Integer.TYPE);
m_getHistoricalX = MotionEvent.class.getMethod("getHistoricalX", Integer.TYPE, Integer.TYPE);
m_getHistoricalY = MotionEvent.class.getMethod("getHistoricalY", Integer.TYPE, Integer.TYPE);
m_getHistoricalPressure = MotionEvent.class.getMethod("getHistoricalPressure", Integer.TYPE, Integer.TYPE);
m_getX = MotionEvent.class.getMethod("getX", Integer.TYPE);
m_getY = MotionEvent.class.getMethod("getY", Integer.TYPE);
succeeded = true;
} catch (Exception e) {
Log.e("MultiTouchController", "static initializer failed", e);
}
multiTouchSupported = succeeded;
if (multiTouchSupported) {
// Android 2.2+ stuff (the original Android 2.2 consts are declared above,
// and these actions aren't used previous to Android 2.2):
try {
ACTION_POINTER_UP = MotionEvent.class.getField("ACTION_POINTER_UP").getInt(null);
ACTION_POINTER_INDEX_SHIFT = MotionEvent.class.getField("ACTION_POINTER_INDEX_SHIFT").getInt(null);
} catch (Exception e) {
}
}
}
// ------------------------------------------------------------------------------------
private static final float[] xVals = new float[MAX_TOUCH_POINTS];
private static final float[] yVals = new float[MAX_TOUCH_POINTS];
private static final float[] pressureVals = new float[MAX_TOUCH_POINTS];
private static final int[] pointerIds = new int[MAX_TOUCH_POINTS];
/** Process incoming touch events */
@SuppressWarnings("unused")
public boolean onTouchEvent(MotionEvent event) {
try {
int pointerCount = multiTouchSupported ? (Integer) m_getPointerCount.invoke(event) : 1;
if (DEBUG)
Log.i("MultiTouch", "Got here 1 - " + multiTouchSupported + " " + mMode + " " + handleSingleTouchEvents + " " + pointerCount);
if (mMode == MODE_NOTHING && !handleSingleTouchEvents && pointerCount == 1)
// Not handling initial single touch events, just pass them on
return false;
if (DEBUG)
Log.i("MultiTouch", "Got here 2");
// Handle history first (we sometimes get history with ACTION_MOVE events)
int action = event.getAction();
int histLen = event.getHistorySize() / pointerCount;
for (int histIdx = 0; histIdx <= histLen; histIdx++) {
// Read from history entries until histIdx == histLen, then read from current event
boolean processingHist = histIdx < histLen;
if (!multiTouchSupported || pointerCount == 1) {
// Use single-pointer methods -- these are needed as a special case (for some weird reason) even if
// multitouch is supported but there's only one touch point down currently -- event.getX(0) etc. throw
// an exception if there's only one point down.
if (DEBUG)
Log.i("MultiTouch", "Got here 3");
xVals[0] = processingHist ? event.getHistoricalX(histIdx) : event.getX();
yVals[0] = processingHist ? event.getHistoricalY(histIdx) : event.getY();
pressureVals[0] = processingHist ? event.getHistoricalPressure(histIdx) : event.getPressure();
} else {
// Read x, y and pressure of each pointer
if (DEBUG)
Log.i("MultiTouch", "Got here 4");
int numPointers = Math.min(pointerCount, MAX_TOUCH_POINTS);
if (DEBUG && pointerCount > MAX_TOUCH_POINTS)
Log.i("MultiTouch", "Got more pointers than MAX_TOUCH_POINTS");
for (int ptrIdx = 0; ptrIdx < numPointers; ptrIdx++) {
int ptrId = (Integer) m_getPointerId.invoke(event, ptrIdx);
pointerIds[ptrIdx] = ptrId;
// N.B. if pointerCount == 1, then the following methods throw an array index out of range exception,
// and the code above is therefore required not just for Android 1.5/1.6 but also for when there is
// only one touch point on the screen -- pointlessly inconsistent :(
xVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalX.invoke(event, ptrIdx, histIdx) : m_getX.invoke(event, ptrIdx));
yVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalY.invoke(event, ptrIdx, histIdx) : m_getY.invoke(event, ptrIdx));
pressureVals[ptrIdx] = (Float) (processingHist ? m_getHistoricalPressure.invoke(event, ptrIdx, histIdx) : m_getPressure
.invoke(event, ptrIdx));
}
}
// Decode event
decodeTouchEvent(pointerCount, xVals, yVals, pressureVals, pointerIds, //
/* action = */processingHist ? MotionEvent.ACTION_MOVE : action, //
/* down = */processingHist ? true : action != MotionEvent.ACTION_UP //
&& (action & ((1 << ACTION_POINTER_INDEX_SHIFT) - 1)) != ACTION_POINTER_UP //
&& action != MotionEvent.ACTION_CANCEL, //
processingHist ? event.getHistoricalEventTime(histIdx) : event.getEventTime());
}
return true;
} catch (Exception e) {
// In case any of the introspection stuff fails (it shouldn't)
Log.e("MultiTouchController", "onTouchEvent() failed", e);
return false;
}
}
private void decodeTouchEvent(int pointerCount, float[] x, float[] y, float[] pressure, int[] pointerIds, int action, boolean down, long eventTime) {
if (DEBUG)
Log.i("MultiTouch", "Got here 5 - " + pointerCount + " " + action + " " + down);
// Swap curr/prev points
PointInfo tmp = mPrevPt;
mPrevPt = mCurrPt;
mCurrPt = tmp;
// Overwrite old prev point
mCurrPt.set(pointerCount, x, y, pressure, pointerIds, action, down, eventTime);
multiTouchController();
}
// ------------------------------------------------------------------------------------
/** Start dragging/pinching, or reset drag/pinch to current point if something goes out of range */
private void anchorAtThisPositionAndScale() {
if (DEBUG)
Log.i("MulitTouch", "anchorAtThisPositionAndScale()");
if (selectedObject == null)
return;
// Get selected object's current position and scale
objectCanvas.getPositionAndScale(selectedObject, mCurrXform);
// Figure out the object coords of the drag start point's screen coords.
// All stretching should be around this point in object-coord-space.
// Also figure out out ratio between object scale factor and multitouch
// diameter at beginning of drag; same for angle and optional anisotropic
// scale.
float currScaleInv = 1.0f / (!mCurrXform.updateScale ? 1.0f : mCurrXform.scale == 0.0f ? 1.0f : mCurrXform.scale);
extractCurrPtInfo();
startPosX = (mCurrPtX - mCurrXform.xOff) * currScaleInv;
startPosY = (mCurrPtY - mCurrXform.yOff) * currScaleInv;
startScaleOverPinchDiam = mCurrXform.scale / mCurrPtDiam;
startScaleXOverPinchWidth = mCurrXform.scaleX / mCurrPtWidth;
startScaleYOverPinchHeight = mCurrXform.scaleY / mCurrPtHeight;
startAngleMinusPinchAngle = mCurrXform.angle - mCurrPtAng;
}
/** Drag/stretch/rotate the selected object using the current touch position(s) relative to the anchor position(s). */
private void performDragOrPinch() {
// Don't do anything if we're not dragging anything
if (selectedObject == null)
return;
// Calc new position of dragged object
float currScale = !mCurrXform.updateScale ? 1.0f : mCurrXform.scale == 0.0f ? 1.0f : mCurrXform.scale;
extractCurrPtInfo();
float newPosX = mCurrPtX - startPosX * currScale;
float newPosY = mCurrPtY - startPosY * currScale;
float newScale = startScaleOverPinchDiam * mCurrPtDiam;
float newScaleX = startScaleXOverPinchWidth * mCurrPtWidth;
float newScaleY = startScaleYOverPinchHeight * mCurrPtHeight;
float newAngle = startAngleMinusPinchAngle + mCurrPtAng;
// Set the new obj coords, scale, and angle as appropriate (notifying the subclass of the change).
mCurrXform.set(newPosX, newPosY, newScale, newScaleX, newScaleY, newAngle);
boolean success = objectCanvas.setPositionAndScale(selectedObject, mCurrXform, mCurrPt);
if (!success)
; // If we could't set those params, do nothing currently
}
/**
* State-based controller for tracking switches between no-touch, single-touch and multi-touch situations. Includes logic for cleaning up the
* event stream, as events around touch up/down are noisy at least on early Synaptics sensors.
*/
private void multiTouchController() {
if (DEBUG)
Log.i("MultiTouch", "Got here 6 - " + mMode + " " + mCurrPt.getNumTouchPoints() + " " + mCurrPt.isDown() + mCurrPt.isMultiTouch());
switch (mMode) {
case MODE_NOTHING:
if (DEBUG)
Log.i("MultiTouch", "MODE_NOTHING");
// Not doing anything currently
if (mCurrPt.isDown()) {
// Start a new single-point drag
selectedObject = objectCanvas.getDraggableObjectAtPoint(mCurrPt);
if (selectedObject != null) {
// Started a new single-point drag
mMode = MODE_DRAG;
objectCanvas.selectObject(selectedObject, mCurrPt);
anchorAtThisPositionAndScale();
// Don't need any settling time if just placing one finger, there is no noise
mSettleStartTime = mSettleEndTime = mCurrPt.getEventTime();
}
}
break;
case MODE_DRAG:
if (DEBUG)
Log.i("MultiTouch", "MODE_DRAG");
// Currently in a single-point drag
if (!mCurrPt.isDown()) {
// First finger was released, stop dragging
mMode = MODE_NOTHING;
objectCanvas.selectObject((selectedObject = null), mCurrPt);
} else if (mCurrPt.isMultiTouch()) {
// Point 1 was already down and point 2 was just placed down
mMode = MODE_PINCH;
// Restart the drag with the new drag position (that is at the midpoint between the touchpoints)
anchorAtThisPositionAndScale();
// Need to let events settle before moving things, to help with event noise on touchdown
mSettleStartTime = mCurrPt.getEventTime();
mSettleEndTime = mSettleStartTime + EVENT_SETTLE_TIME_INTERVAL;
} else {
// Point 1 is still down and point 2 did not change state, just do single-point drag to new location
if (mCurrPt.getEventTime() < mSettleEndTime) {
// Ignore the first few events if we just stopped stretching, because if finger 2 was kept down while
// finger 1 is lifted, then point 1 gets mapped to finger 2. Restart the drag from the new position.
anchorAtThisPositionAndScale();
} else {
// Keep dragging, move to new point
performDragOrPinch();
}
}
break;
case MODE_PINCH:
if (DEBUG)
Log.i("MultiTouch", "MODE_PINCH");
// Two-point pinch-scale/rotate/translate
if (!mCurrPt.isMultiTouch() || !mCurrPt.isDown()) {
// Dropped one or both points, stop stretching
if (!mCurrPt.isDown()) {
// Dropped both points, go back to doing nothing
mMode = MODE_NOTHING;
objectCanvas.selectObject((selectedObject = null), mCurrPt);
} else {
// Just dropped point 2, downgrade to a single-point drag
mMode = MODE_DRAG;
// Restart the pinch with the single-finger position
anchorAtThisPositionAndScale();
// Ignore the first few events after the drop, in case we dropped finger 1 and left finger 2 down
mSettleStartTime = mCurrPt.getEventTime();
mSettleEndTime = mSettleStartTime + EVENT_SETTLE_TIME_INTERVAL;
}
} else {
// Still pinching
if (Math.abs(mCurrPt.getX() - mPrevPt.getX()) > MAX_MULTITOUCH_POS_JUMP_SIZE
|| Math.abs(mCurrPt.getY() - mPrevPt.getY()) > MAX_MULTITOUCH_POS_JUMP_SIZE
|| Math.abs(mCurrPt.getMultiTouchWidth() - mPrevPt.getMultiTouchWidth()) * .5f > MAX_MULTITOUCH_DIM_JUMP_SIZE
|| Math.abs(mCurrPt.getMultiTouchHeight() - mPrevPt.getMultiTouchHeight()) * .5f > MAX_MULTITOUCH_DIM_JUMP_SIZE) {
// Jumped too far, probably event noise, reset and ignore events for a bit
anchorAtThisPositionAndScale();
mSettleStartTime = mCurrPt.getEventTime();
mSettleEndTime = mSettleStartTime + EVENT_SETTLE_TIME_INTERVAL;
} else if (mCurrPt.eventTime < mSettleEndTime) {
// Events have not yet settled, reset
anchorAtThisPositionAndScale();
} else {
// Stretch to new position and size
performDragOrPinch();
}
}
break;
}
if (DEBUG)
Log.i("MultiTouch", "Got here 7 - " + mMode + " " + mCurrPt.getNumTouchPoints() + " " + mCurrPt.isDown() + mCurrPt.isMultiTouch());
}
public int getMode() {
return mMode;
}
/** A class that packages up all MotionEvent information with all derived multitouch information (if available) */
public static class PointInfo {
// Multitouch information
private int numPoints;
private float[] xs = new float[MAX_TOUCH_POINTS];
private float[] ys = new float[MAX_TOUCH_POINTS];
private float[] pressures = new float[MAX_TOUCH_POINTS];
private int[] pointerIds = new int[MAX_TOUCH_POINTS];
// Midpoint of pinch operations
private float xMid, yMid, pressureMid;
// Width/diameter/angle of pinch operations
private float dx, dy, diameter, diameterSq, angle;
// Whether or not there is at least one finger down (isDown) and/or at least two fingers down (isMultiTouch)
private boolean isDown, isMultiTouch;
// Whether or not these fields have already been calculated, for caching purposes
private boolean diameterSqIsCalculated, diameterIsCalculated, angleIsCalculated;
// Event action code and event time
private int action;
private long eventTime;
// -------------------------------------------------------------------------------------------------------------------------------------------
/** Set all point info */
private void set(int numPoints, float[] x, float[] y, float[] pressure, int[] pointerIds, int action, boolean isDown, long eventTime) {
if (DEBUG)
Log.i("MultiTouch", "Got here 8 - " + +numPoints + " " + x[0] + " " + y[0] + " " + (numPoints > 1 ? x[1] : x[0]) + " "
+ (numPoints > 1 ? y[1] : y[0]) + " " + action + " " + isDown);
this.eventTime = eventTime;
this.action = action;
this.numPoints = numPoints;
for (int i = 0; i < numPoints; i++) {
this.xs[i] = x[i];
this.ys[i] = y[i];
this.pressures[i] = pressure[i];
this.pointerIds[i] = pointerIds[i];
}
this.isDown = isDown;
this.isMultiTouch = numPoints >= 2;
if (isMultiTouch) {
xMid = (x[0] + x[1]) * .5f;
yMid = (y[0] + y[1]) * .5f;
pressureMid = (pressure[0] + pressure[1]) * .5f;
dx = Math.abs(x[1] - x[0]);
dy = Math.abs(y[1] - y[0]);
} else {
// Single-touch event
xMid = x[0];
yMid = y[0];
pressureMid = pressure[0];
dx = dy = 0.0f;
}
// Need to re-calculate the expensive params if they're needed
diameterSqIsCalculated = diameterIsCalculated = angleIsCalculated = false;
}
/**
* Copy all fields from one PointInfo class to another. PointInfo objects are volatile so you should use this if you want to keep track of the
* last touch event in your own code.
*/
public void set(PointInfo other) {
this.numPoints = other.numPoints;
for (int i = 0; i < numPoints; i++) {
this.xs[i] = other.xs[i];
this.ys[i] = other.ys[i];
this.pressures[i] = other.pressures[i];
this.pointerIds[i] = other.pointerIds[i];
}
this.xMid = other.xMid;
this.yMid = other.yMid;
this.pressureMid = other.pressureMid;
this.dx = other.dx;
this.dy = other.dy;
this.diameter = other.diameter;
this.diameterSq = other.diameterSq;
this.angle = other.angle;
this.isDown = other.isDown;
this.action = other.action;
this.isMultiTouch = other.isMultiTouch;
this.diameterIsCalculated = other.diameterIsCalculated;
this.diameterSqIsCalculated = other.diameterSqIsCalculated;
this.angleIsCalculated = other.angleIsCalculated;
this.eventTime = other.eventTime;
}
// -------------------------------------------------------------------------------------------------------------------------------------------
/** True if number of touch points >= 2. */
public boolean isMultiTouch() {
return isMultiTouch;
}
/** Difference between x coords of touchpoint 0 and 1. */
public float getMultiTouchWidth() {
return isMultiTouch ? dx : 0.0f;
}
/** Difference between y coords of touchpoint 0 and 1. */
public float getMultiTouchHeight() {
return isMultiTouch ? dy : 0.0f;
}
/** Fast integer sqrt, by Jim Ulery. Much faster than Math.sqrt() for integers. */
private int julery_isqrt(int val) {
int temp, g = 0, b = 0x8000, bshft = 15;
do {
if (val >= (temp = (((g << 1) + b) << bshft--))) {
g += b;
val -= temp;
}
} while ((b >>= 1) > 0);
return g;
}
/** Calculate the squared diameter of the multitouch event, and cache it. Use this if you don't need to perform the sqrt. */
public float getMultiTouchDiameterSq() {
if (!diameterSqIsCalculated) {
diameterSq = (isMultiTouch ? dx * dx + dy * dy : 0.0f);
diameterSqIsCalculated = true;
}
return diameterSq;
}
/** Calculate the diameter of the multitouch event, and cache it. Uses fast int sqrt but gives accuracy to 1/16px. */
public float getMultiTouchDiameter() {
if (!diameterIsCalculated) {
if (!isMultiTouch) {
diameter = 0.0f;
} else {
// Get 1/16 pixel's worth of subpixel accuracy, works on screens up to 2048x2048
// before we get overflow (at which point you can reduce or eliminate subpix
// accuracy, or use longs in julery_isqrt())
float diamSq = getMultiTouchDiameterSq();
diameter = (diamSq == 0.0f ? 0.0f : (float) julery_isqrt((int) (256 * diamSq)) / 16.0f);
// Make sure diameter is never less than dx or dy, for trig purposes
if (diameter < dx)
diameter = dx;
if (diameter < dy)
diameter = dy;
}
diameterIsCalculated = true;
}
return diameter;
}
/**
* Calculate the angle of a multitouch event, and cache it. Actually gives the smaller of the two angles between the x axis and the line
* between the two touchpoints, so range is [0,Math.PI/2]. Uses Math.atan2().
*/
public float getMultiTouchAngle() {
if (!angleIsCalculated) {
if (!isMultiTouch)
angle = 0.0f;
else
angle = (float) Math.atan2(ys[1] - ys[0], xs[1] - xs[0]);
angleIsCalculated = true;
}
return angle;
}
// -------------------------------------------------------------------------------------------------------------------------------------------
/** Return the total number of touch points */
public int getNumTouchPoints() {
return numPoints;
}
/** Return the X coord of the first touch point if there's only one, or the midpoint between first and second touch points if two or more. */
public float getX() {
return xMid;
}
/** Return the array of X coords -- only the first getNumTouchPoints() of these is defined. */
public float[] getXs() {
return xs;
}
/** Return the X coord of the first touch point if there's only one, or the midpoint between first and second touch points if two or more. */
public float getY() {
return yMid;
}
/** Return the array of Y coords -- only the first getNumTouchPoints() of these is defined. */
public float[] getYs() {
return ys;
}
/**
* Return the array of pointer ids -- only the first getNumTouchPoints() of these is defined. These don't have to be all the numbers from 0 to
* getNumTouchPoints()-1 inclusive, numbers can be skipped if a finger is lifted and the touch sensor is capable of detecting that that
* particular touch point is no longer down. Note that a lot of sensors do not have this capability: when finger 1 is lifted up finger 2
* becomes the new finger 1. However in theory these IDs can correct for that. Convert back to indices using MotionEvent.findPointerIndex().
*/
public int[] getPointerIds() {
return pointerIds;
}
/** Return the pressure the first touch point if there's only one, or the average pressure of first and second touch points if two or more. */
public float getPressure() {
return pressureMid;
}
/** Return the array of pressures -- only the first getNumTouchPoints() of these is defined. */
public float[] getPressures() {
return pressures;
}
// -------------------------------------------------------------------------------------------------------------------------------------------
public boolean isDown() {
return isDown;
}
public int getAction() {
return action;
}
public long getEventTime() {
return eventTime;
}
}
// ------------------------------------------------------------------------------------
/**
* A class that is used to store scroll offsets and scale information for objects that are managed by the multitouch controller
*/
public static class PositionAndScale {
private float xOff, yOff, scale, scaleX, scaleY, angle;
private boolean updateScale, updateScaleXY, updateAngle;
/**
* Set position and optionally scale, anisotropic scale, and/or angle. Where if the corresponding "update" flag is set to false, the field's
* value will not be changed during a pinch operation. If the value is not being updated *and* the value is not used by the client
* application, then the value can just be zero. However if the value is not being updated but the value *is* being used by the client
* application, the value should still be specified and the update flag should be false (e.g. angle of the object being dragged should still
* be specified even if the program is in "resize" mode rather than "rotate" mode).
*/
public void set(float xOff, float yOff, boolean updateScale, float scale, boolean updateScaleXY, float scaleX, float scaleY,
boolean updateAngle, float angle) {
this.xOff = xOff;
this.yOff = yOff;
this.updateScale = updateScale;
this.scale = scale == 0.0f ? 1.0f : scale;
this.updateScaleXY = updateScaleXY;
this.scaleX = scaleX == 0.0f ? 1.0f : scaleX;
this.scaleY = scaleY == 0.0f ? 1.0f : scaleY;
this.updateAngle = updateAngle;
this.angle = angle;
}
/** Set position and optionally scale, anisotropic scale, and/or angle, without changing the "update" flags. */
protected void set(float xOff, float yOff, float scale, float scaleX, float scaleY, float angle) {
this.xOff = xOff;
this.yOff = yOff;
this.scale = scale == 0.0f ? 1.0f : scale;
this.scaleX = scaleX == 0.0f ? 1.0f : scaleX;
this.scaleY = scaleY == 0.0f ? 1.0f : scaleY;
this.angle = angle;
}
public float getXOff() {
return xOff;
}
public float getYOff() {
return yOff;
}
public float getScale() {
return !updateScale ? 1.0f : scale;
}
/** Included in case you want to support anisotropic scaling */
public float getScaleX() {
return !updateScaleXY ? 1.0f : scaleX;
}
/** Included in case you want to support anisotropic scaling */
public float getScaleY() {
return !updateScaleXY ? 1.0f : scaleY;
}
public float getAngle() {
return !updateAngle ? 0.0f : angle;
}
}
// ------------------------------------------------------------------------------------
public static interface MultiTouchObjectCanvas<T> {
/**
* See if there is a draggable object at the current point. Returns the object at the point, or null if nothing to drag. To start a multitouch
* drag/stretch operation, this routine must return some non-null reference to an object. This object is passed into the other methods in this
* interface when they are called.
*
* @param touchPoint
* The point being tested (in object coordinates). Return the topmost object under this point, or if dragging/stretching the whole
* canvas, just return a reference to the canvas.
* @return a reference to the object under the point being tested, or null to cancel the drag operation. If dragging/stretching the whole
* canvas (e.g. in a photo viewer), always return non-null, otherwise the stretch operation won't work.
*/
public T getDraggableObjectAtPoint(PointInfo touchPoint);
/**
* Get the screen coords of the dragged object's origin, and scale multiplier to convert screen coords to obj coords. The job of this routine
* is to call the .set() method on the passed PositionAndScale object to record the initial position and scale of the object (in object
* coordinates) before any dragging/stretching takes place.
*
* @param obj
* The object being dragged/stretched.
* @param objPosAndScaleOut
* Output parameter: You need to call objPosAndScaleOut.set() to record the current position and scale of obj.
*/
public void getPositionAndScale(T obj, PositionAndScale objPosAndScaleOut);
/**
* Callback to update the position and scale (in object coords) of the currently-dragged object.
*
* @param obj
* The object being dragged/stretched.
* @param newObjPosAndScale
* The new position and scale of the object, in object coordinates. Use this to move/resize the object before returning.
* @param touchPoint
* Info about the current touch point, including multitouch information and utilities to calculate and cache multitouch pinch
* diameter etc. (Note: touchPoint is volatile, if you want to keep any fields of touchPoint, you must copy them before the method
* body exits.)
* @return true if setting the position and scale of the object was successful, or false if the position or scale parameters are out of range
* for this object.
*/
public boolean setPositionAndScale(T obj, PositionAndScale newObjPosAndScale, PointInfo touchPoint);
/**
* Select an object at the given point. Can be used to bring the object to top etc. Only called when first touchpoint goes down, not when
* multitouch is initiated. Also called with null on touch-up.
*
* @param obj
* The object being selected by single-touch, or null on touch-up.
* @param touchPoint
* The current touch point.
*/
public void selectObject(T obj, PointInfo touchPoint);
}
}
| Java |
package fabworkz.anna;
import java.util.ArrayList;
import root.gast.speech.activation.SpeechActivationService;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class SpeechRecognitionLauncher extends Activity {
private static final String TAG = "SpeechRecognitionLauncher";
private static final int VOICE_RECOGNITION_REQUEST_CODE = 101010;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
// PowerManager.WakeLock lck = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
// lck.acquire(1000);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
//sleep a bit to wait for screen to wake up
// try {
// Thread.sleep(5000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
@Override
protected void onStart(){
super.onStart();
Intent recognizerIntent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Listening ..");
recognizerIntent.setFlags(Intent.FLAG_FROM_BACKGROUND);
startActivityForResult(recognizerIntent,VOICE_RECOGNITION_REQUEST_CODE);
}
@Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
if(matches.get(0).equals("Google")){
Log.d("ANNA", "heard Google, launching voice search..");
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
// Intent showResults = new Intent(data);
// showResults.setClass(this,
// SpeechRecognitionResultsActivity.class);
// startActivity(showResults);
Log.d(TAG,"result ok");
// Intent stopService = SpeechActivationService.makeServiceStopIntent(this);
// startService(stopService);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}
Intent i = SpeechActivationService.makeStartServiceIntent(this,
"clapper",8000);
startService(i);
finish();
}
}
| Java |
package fabworkz.anna;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
//import android.widget.ArrayAdapter;
public class VoiceRecognition extends Activity {
private static int REQUEST_CODE=1010;
// private ListView wordsList;
private SpeechRecognizer sr;
/**
* Called with the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_recognition);
Log.d("ANNA", "voice recognition class created");
// sr = SpeechRecognizer.createSpeechRecognizer(this);
// sr.setRecognitionListener(new listener());
//wordsList = (ListView) findViewById(R.id.list);
// Disable button if no recognition service is present
// PackageManager pm = getPackageManager();
// List<ResolveInfo> activities = pm.queryIntentActivities(
// new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
// if (activities.size() != 0)
// {
startVoiceRecognitionActivity();
//finish();
// }
}
/**
* Handle the action of the button being clicked
*/
/**
* Fire an intent to start the voice recognition activity.
*/
private void startVoiceRecognitionActivity()
{
Log.d("ANNA", "Starting voice recognition activity");
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Listening...");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 5);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"fabworkz.anna");
startActivityForResult(intent, REQUEST_CODE);
//sr.startListening(intent);
}
/**
* Handle the results from the voice recognition activity.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK)
{
// Populate the wordsList with the String values the recognition engine thought it heard
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
if(matches.get(0).equals("Google")){
Log.d("ANNA", "heard Google, launching voice search..");
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(matches.get(0).equals("Computer")){
Log.d("ANNA","heard computer, listening for more..");
startVoiceRecognitionActivity();
}
else if(matches.get(0).equals("stop")){
Log.d("ANNA","heard stop, finishing up..");
}
//wordsList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
// matches));
}
super.onActivityResult(requestCode, resultCode, data);
}
class listener implements RecognitionListener
{
private static final String TAG = "ANNA RecognitionListener";
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
}
public void onResults(Bundle results)
{
Log.d(TAG, "onResults " + results);
ArrayList<String> matches = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
if(matches.get(0).equals("Google")){
Log.d("ANNA", "heard Google, launching voice search..");
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
startActivity(intent);
finish();
}
else if(matches.get(0).equals("Computer")){
Log.d("ANNA", "heard Computer, waiting for more..");
//startVoiceRecognitionActivity();
}
else if(matches.get(0).equals("stop")){
finish();
}
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
// public void finish(String command) {
// // Prepare data intent
// Intent data = new Intent();
// data.putExtra("returnKey1", command);
//
// /*
// data.putExtra("returnKey2", "You could be better then you are. ");*/
// // Activity finished ok, return the data
// setResult(RESULT_OK, data);
// super.finish();
// }
}
| Java |
package fabworkz.anna;
import java.lang.ref.WeakReference;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
public class BackgroundService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
private static final String TAG = "BackgroundService";
@Override
public void onCreate()
{
super.onCreate();
Log.d(TAG,"VoiceRec service created..");
mAudioManager = (AudioManager) getSystemService(BackgroundService.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
try {
mServerMessenger.send(Message.obtain(null, MSG_RECOGNIZER_START_LISTENING));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected static class IncomingHandler extends Handler
{
private WeakReference<BackgroundService> mtarget;
IncomingHandler(BackgroundService target)
{
mtarget = new WeakReference<BackgroundService>(target);
}
@Override
public void handleMessage(Message msg)
{
final BackgroundService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d(TAG, "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d(TAG, "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
@Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
@Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
@Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
private static final String TAG = "RecognitionListener";
@Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
@Override
public void onBufferReceived(byte[] buffer)
{
}
@Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
}
@Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
@Override
public void onEvent(int eventType, Bundle params)
{
}
@Override
public void onPartialResults(Bundle partialResults)
{
}
@Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d(TAG, "onReadyForSpeech"); //$NON-NLS-1$
}
@Override
public void onResults(Bundle results)
{
Log.d(TAG, "onResults"); //$NON-NLS-1$
}
@Override
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
} | Java |
package fabworkz.anna;
import root.gast.speech.activation.SpeechActivationService;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
// private static final String TAG = "ANNA";
// private RecordAudioTask recordAudioTask;
// private RecordAmplitudeTask recordAmplitudeTask;
// private static final int REQUEST_CODE = 1010;
// private static final int REQUEST_CODE = 1010;
// private Intent intent;
// private Messenger messenger;
//
// private Handler handler = new Handler() {
// public void handleMessage(Message message) {
// Object obj = message.obj;
// if (message.arg1 == RESULT_OK && obj != null) {
// //startVoiceRecognitionActivity();
// } else {
// Toast.makeText(MainActivity.this, "Download failed.",
// Toast.LENGTH_LONG).show();
// }
//
// };
// };
/**
* Handle the action of the button being clicked
*/
private static final String TAG = "ANNAMain";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.speechactivationservice);
startService("clapper");
finish();
// hookButtons();
}
// private void hookButtons()
// {
// List<Button> startButtons = new ArrayList<Button>();
// startButtons.add(makeStartButton(R.id.btn_speech_activation_movement, R.string.speech_activation_movement));
// startButtons.add(makeStartButton(R.id.btn_speech_activation_clap, R.string.speech_activation_clap));
// startButtons.add(makeStartButton(R.id.btn_speech_activation_camera, R.string.speech_activation_camera));
// startButtons.add(makeStartButton(R.id.btn_speech_activation_speak, R.string.speech_activation_speak));
// }
private void stopService(){
Log.d(TAG, "stop service");
Intent i = SpeechActivationService.makeServiceStopIntent(this);
startService(i);
}
private void startService(String name){
String activationTypeName = name;
Intent i = SpeechActivationService.makeStartServiceIntent(this,
activationTypeName,0);
startService(i);
Log.d(TAG, "started service for " + activationTypeName);
}
}
| Java |
package fabworkz.anna;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class ServiceLauncher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, fabworkz.anna.BackgroundService.class);
this.startService(intent);
finish();
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.ArrayList;
import java.util.List;
import root.gast.speech.SpeechRecognizingAndSpeakingActivity;
import root.gast.speech.activation.SpeechActivationService;
import root.gast.speech.tts.TextToSpeechUtils;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
/**
* Starts a speech recognition dialog and then sends the results to
* {@link SpeechRecognitionResultsActivity}
*
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class SpeechRecognitionLauncher extends
SpeechRecognizingAndSpeakingActivity
{
private static final String TAG = "SpeechRecognitionLauncher";
private static final String ON_DONE_PROMPT_TTS_PARAM = "ON_DONE_PROMPT";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public void onSuccessfulInit(TextToSpeech tts)
{
super.onSuccessfulInit(tts);
//prompt();
listenForInput();
}
// private void prompt()
// {
// Log.d(TAG, "Speak prompt");
// getTts().speak("Speak a test phrase",
// TextToSpeech.QUEUE_FLUSH,
// TextToSpeechUtils.makeParamsWith(ON_DONE_PROMPT_TTS_PARAM));
// }
/**
* super class handles registering the UtteranceProgressListener
* and calling this
*/
@Override
public void onDone(String utteranceId)
{
if (utteranceId.equals(ON_DONE_PROMPT_TTS_PARAM))
{
Intent recognizerIntent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Please speak ..");
recognize(recognizerIntent);
}
}
public void listenForInput()
{
Intent recognizerIntent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Listening ..");
recognize(recognizerIntent);
}
@Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
ArrayList<String> matches = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS);
if(matches.get(0).equals("Google")){
Log.d("ANNA", "heard Google, launching voice search..");
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
// Intent showResults = new Intent(data);
// showResults.setClass(this,
// SpeechRecognitionResultsActivity.class);
// startActivity(showResults);
Log.d(TAG,"result ok");
// Intent stopService = SpeechActivationService.makeServiceStopIntent(this);
// startService(stopService);
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
Intent startService = SpeechActivationService.makeStartServiceIntent(this,
"clapper",20000);
startService(startService);
}
}
finish();
}
@Override
protected void receiveWhatWasHeard(List<String> heard,
float[] confidenceScores)
{
// satisfy abstract class, this class handles the results directly
// instead of using this method
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import android.content.Intent;
import android.speech.RecognizerIntent;
/**
* helps create {@link RecognizerIntent}s
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class RecognizerIntentFactory
{
public static final int ACTION_GET_LANGUAGE_DETAILS_REQUEST_CODE = 88811;
private static final int DEFAUT_MAX_RESULTS = 100;
public static Intent getSimpleRecognizerIntent(String prompt)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
return intent;
}
public static Intent getBlankRecognizeIntent()
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
return intent;
}
public static Intent getWebSearchRecognizeIntent()
{
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
return intent;
}
public static Intent getPossilbeWebSearchRecognizeIntent(String prompt)
{
Intent intent = new Intent(RecognizerIntent.ACTION_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, prompt);
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, DEFAUT_MAX_RESULTS);
intent.putExtra(RecognizerIntent.EXTRA_WEB_SEARCH_ONLY, false);
intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
// intent.putExtra(RecognizerIntent.ORIGIN, "http://www.github.com/gast-lib");
return intent;
}
public static Intent getLanguageDetailsIntent()
{
Intent intent = new Intent(RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
return intent;
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public interface OnLanguageDetailsListener
{
public void onLanguageDetailsReceived(LanguageDetailsChecker data);
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.List;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class ActionLanguageDetailsLogger extends BroadcastReceiver
{
private static final String TAG = "ActionLanguageDetailsLogger";
@Override
public void onReceive(Context context, Intent intent)
{
Bundle results = getResultExtras(true);
Log.d(TAG,
"RECIEVED! get language details broadcast "
+ results);
}
public String getDescription()
{
Bundle results = getResultExtras(true);
StringBuilder sb = new StringBuilder();
if (results
.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE))
{
String lang = results
.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE);
sb.append("Language Preference: ")
.append(lang).append("\n");
}
if (results
.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES))
{
List<String> langs = results
.getStringArrayList(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES);
sb.append("languages supported: ").append(
"\n");
for (String lang : langs)
{
sb.append(" ").append(lang)
.append("\n");
}
}
Log.d(TAG, sb.toString());
return sb.toString();
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
/**
* receives the speech recognition language details from
* RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS and
* then calls back to a {@link OnLanguageDetailsListener}
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class LanguageDetailsChecker extends BroadcastReceiver
{
private static final String TAG = "LanguageDetailsChecker";
private List<String> supportedLanguages;
private String languagePreference;
private OnLanguageDetailsListener doAfterReceive;
public LanguageDetailsChecker(OnLanguageDetailsListener doAfterReceive)
{
supportedLanguages = new ArrayList<String>();
this.doAfterReceive = doAfterReceive;
}
@Override
public void onReceive(Context context, Intent intent)
{
Bundle results = getResultExtras(true);
if (results.containsKey(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE))
{
languagePreference =
results.getString(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE);
}
if (results.containsKey(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES))
{
supportedLanguages =
results.getStringArrayList(
RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES);
}
if (doAfterReceive != null)
{
doAfterReceive.onLanguageDetailsReceived(this);
}
}
public String matchLanguage(Locale toCheck)
{
String matchedLanguage = null;
// modify the returned languages to look like the output from
// Locale.toString()
String targetLanguage = toCheck.toString().replace('_', '-');
for (String supportedLanguage : supportedLanguages)
{
// use contains, so that partial matches are possible
// for example, if the Locale is
// en-US-POSIX, it will still match en-US
// and that if the target language is en, it will match something
Log.d(TAG, targetLanguage + " contains " + supportedLanguage);
if ((targetLanguage.contains(supportedLanguage))
|| supportedLanguage.contains(targetLanguage))
{
matchedLanguage = supportedLanguage;
}
}
return matchedLanguage;
}
/**
* @return the supportedLanguages
*/
public List<String> getSupportedLanguages()
{
return supportedLanguages;
}
/**
* @return the languagePreference
*/
public String getLanguagePreference()
{
return languagePreference;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Language Preference: ").append(getLanguagePreference())
.append("\n");
sb.append("languages supported: ").append("\n");
for (String lang : getSupportedLanguages())
{
sb.append(" ").append(lang).append("\n");
}
return sb.toString();
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class SupportedVoices
{
public static String ENGLISH_USA = "eng-USA";
public static String ENGLISH_BRITISH = "eng-GBR";
public static String SPANISH = "spa-ESP";
public static String GERMAN = "deu-DEU";
public static String ITALIAN = "ita-ITA";
public static String FRENCH = "fr-FRA";
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import java.util.Locale;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
/**
* Helps construct an initalized {@link TextToSpeech}
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class TextToSpeechInitializer
{
private static final String TAG = "TextToSpeechInitializer";
private TextToSpeech tts;
private TextToSpeechStartupListener callback;
private Context context;
/**
* creates by checking {@link TextToSpeech#isLanguageAvailable(Locale)}
*/
public TextToSpeechInitializer(Context context, final Locale loc,
TextToSpeechStartupListener callback)
{
this.callback = callback;
this.context = context;
createTextToSpeech(loc);
}
/**
* creating a TTS
* @param locale {@link Locale} for the desired language
*/
private void createTextToSpeech(final Locale locale)
{
tts = new TextToSpeech(context, new OnInitListener()
{
@Override
public void onInit(int status)
{
if (status == TextToSpeech.SUCCESS)
{
setTextToSpeechSettings(locale);
} else
{
Log.e(TAG, "error creating text to speech");
callback.onFailedToInit();
}
}
});
}
/**
* perform the initialization checks after the
* TextToSpeech is done
*/
private void setTextToSpeechSettings(final Locale locale)
{
Locale defaultOrPassedIn = locale;
if (locale == null)
{
defaultOrPassedIn = Locale.getDefault();
}
// check if language is available
switch (tts.isLanguageAvailable(defaultOrPassedIn))
{
case TextToSpeech.LANG_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
Log.d(TAG, "SUPPORTED");
tts.setLanguage(locale);
callback.onSuccessfulInit(tts);
break;
case TextToSpeech.LANG_MISSING_DATA:
Log.d(TAG, "MISSING_DATA");
// check if waiting, by checking
// a shared preference
if (LanguageDataInstallBroadcastReceiver
.isWaiting(context))
{
Log.d(TAG, "waiting for data...");
callback.onWaitingForLanguageData();
} else
{
Log.d(TAG, "require data...");
callback.onRequireLanguageData();
}
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
Log.d(TAG, "NOT SUPPORTED");
callback.onFailedToInit();
break;
}
}
public void setOnUtteranceCompleted(OnUtteranceCompletedListener whenDoneSpeaking)
{
int result = tts.setOnUtteranceCompletedListener(whenDoneSpeaking);
if (result == TextToSpeech.ERROR)
{
Log.e(TAG, "failed to add utterance listener");
}
}
/**
* helper method to display a dialog if waiting for a download
*/
public void installLanguageData(Dialog ifAlreadyWaiting)
{
boolean alreadyDidThis = LanguageDataInstallBroadcastReceiver
.isWaiting(context);
if (alreadyDidThis)
{
// give the user the ability to try again..
// throw exception here?
ifAlreadyWaiting.show();
} else
{
installLanguageData();
}
}
public void installLanguageData()
{
// set waiting for the download
LanguageDataInstallBroadcastReceiver.setWaiting(context, true);
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
context.startActivity(installIntent);
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import android.speech.tts.TextToSpeech;
/**
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public interface TextToSpeechStartupListener
{
/**
* tts is initialized and ready for use
*
* @param tts
* the fully initialized object
*/
public void onSuccessfulInit(TextToSpeech tts);
/**
* language data is required, to install call
* {@link TextToSpeechInitializer#installLanguageData()}
*/
public void onRequireLanguageData();
/**
* The app has already requested language data, and is waiting for it.
*/
public void onWaitingForLanguageData();
/**
* initialization failed and can never complete.
*/
public void onFailedToInit();
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class CommonTtsMethods
{
private static final String TAG = "CommonTtsMethods";
private static final String NEW_LINE = "\n";
public static final int SPEECH_DATA_CHECK_CODE = 19327;
/**
* start the language data install
*/
public static void installLanguageData(final Context context)
{
//waiting for the download
LanguageDataInstallBroadcastReceiver.setWaiting(context, true);
//don't actually do it in test mode, just register a receiver
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
context.startActivity(installIntent);
}
/**
* get a descriptions of all the languages available as determined by
* {@link TextToSpeech#isLanguageAvailable(Locale)}
*/
public static String getLanguageAvailableDescription(TextToSpeech tts)
{
StringBuilder sb = new StringBuilder();
for (Locale loc : Locale.getAvailableLocales())
{
int availableCheck = tts.isLanguageAvailable(loc);
sb.append(loc.toString()).append(" ");
switch (availableCheck)
{
case TextToSpeech.LANG_AVAILABLE:
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
sb.append("COUNTRY_AVAILABLE");
break;
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
sb.append("COUNTRY_VAR_AVAILABLE");
break;
case TextToSpeech.LANG_MISSING_DATA:
sb.append("MISSING_DATA");
break;
case TextToSpeech.LANG_NOT_SUPPORTED:
sb.append("NOT_SUPPORTED");
break;
}
sb.append(NEW_LINE);
}
return sb.toString();
}
public static void startDataCheck(Activity callingActivity)
{
Log.d(TAG, "launching speech check");
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
callingActivity.startActivityForResult(checkIntent,
SPEECH_DATA_CHECK_CODE);
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
/**
* Helps construct an initalized {@link TextToSpeech} using the
* TextToSpeech.Engine.ACTION_CHECK_TTS_DATA
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class TextToSpeechInitializerByAction
{
private static final String TAG = "TextToSpeechInitializerByAction";
private TextToSpeech tts;
private TextToSpeechStartupListener callback;
private Activity activity;
private Locale targetLocale;
/**
* creates by checking {@link TextToSpeech#isLanguageAvailable(Locale)}
*/
public TextToSpeechInitializerByAction(Activity activity, String voiceToCheck,
TextToSpeechStartupListener callback, Locale targetLocale)
{
this.callback = callback;
this.activity = activity;
this.targetLocale = targetLocale;
startDataCheck(activity, voiceToCheck);
}
/**
* version of the constructor that converts the {@link Locale}
* to the proper voice to check
*/
public TextToSpeechInitializerByAction(Activity activity,
TextToSpeechStartupListener callback, Locale targetLocale)
{
this(activity, convertLocaleToVoice(targetLocale),
callback, targetLocale);
}
/**
* voice name as defined by
* {@link TextToSpeech.Engine#EXTRA_CHECK_VOICE_DATA_FOR}
*/
public void startDataCheck(Activity activity, String voiceToCheck)
{
Intent check = new Intent();
check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
Log.d(TAG, "launching speech check");
if (voiceToCheck != null && voiceToCheck.length() > 0)
{
Log.d(TAG, "adding voice check for: " + voiceToCheck);
// needs to be in an ArrayList
ArrayList<String> voicesToCheck = new ArrayList<String>();
voicesToCheck.add(voiceToCheck);
check.putStringArrayListExtra(
TextToSpeech.Engine.EXTRA_CHECK_VOICE_DATA_FOR,
voicesToCheck);
}
activity.startActivityForResult(check,
CommonTtsMethods.SPEECH_DATA_CHECK_CODE);
}
/**
* handle onActivityResult from call to
* {@link #startDataCheck(Activity, String)}
*/
public void handleOnActivityResult(Context launchFrom,
int requestCode, int resultCode, Intent data)
{
if (requestCode == CommonTtsMethods.SPEECH_DATA_CHECK_CODE)
{
switch (resultCode)
{
case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS:
// success, create the TTS instance
Log.d(TAG, "has language data");
tts = new TextToSpeech(launchFrom, new OnInitListener()
{
@Override
public void onInit(int status)
{
if (targetLocale != null)
{
tts.setLanguage(targetLocale);
}
if (status == TextToSpeech.SUCCESS)
{
callback.onSuccessfulInit(tts);
} else
{
callback.onFailedToInit();
}
}
});
break;
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME:
case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL:
case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA:
case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA:
Log.d(TAG, "no language data");
callback.onRequireLanguageData();
}
}
}
public void installLanguageData()
{
// waiting for the download
LanguageDataInstallBroadcastReceiver.setWaiting(activity, true);
// don't actually do it in test mode, just register a receiver
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
activity.startActivity(installIntent);
}
public static String convertLocaleToVoice(Locale loc)
{
// The format of each voice is: lang-COUNTRY-variant where COUNTRY and
// variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").
String country = loc.getISO3Country();
String language = loc.getISO3Language();
StringBuilder sb = new StringBuilder();
sb.append(language);
if (country.length() > 0)
{
sb.append("-");
sb.append(country);
}
return sb.toString();
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class TextToSpeechUtils
{
private static final String TAG = "TextToSpeechUtils";
private static final String NEW_LINE = "\n";
public static HashMap<String, String> EMPTY_PARAMS = new HashMap<String, String>();
static
{
EMPTY_PARAMS = makeParamsWith("dummy_id");
}
public static HashMap<String, String> makeParamsWith(String key)
{
HashMap<String, String> params = new HashMap<String, String>();
params.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, key);
return params;
}
/**
* need to get the list and then try to return a best match
*/
private String convertToVoiceCheck(Locale loc, List<String> possibleVoices)
{
// // The format of each voice is: lang-COUNTRY-variant where COUNTRY and
// // variant are optional (ie, "eng" or "eng-USA" or "eng-USA-FEMALE").
//you can't derive the voice from the loc, the best we can do is a best match
if (possibleVoices.size() == 0)
{
return null;
}
//try to match the country?
String bestMatchVoice = null;
String countryToMatch = loc.getISO3Language();
for (String possibleVoice : possibleVoices)
{
if (possibleVoice.toLowerCase().contains(countryToMatch))
{
bestMatchVoice = possibleVoice;
}
}
//handle english because it has a variant
if (bestMatchVoice.contains("eng"))
{
//check country..
if (loc.getCountry().equals("US"))
{
bestMatchVoice = "eng-USA";
}
else
{
bestMatchVoice = "eng-GBR";
}
}
return bestMatchVoice;
}
public static List<Locale> getLocalesSupported(Context context, TextToSpeech tts)
{
List<Locale> supportedLocales = new ArrayList<Locale>();
for (Locale loc : Locale.getAvailableLocales())
{
if (isLanguageAvailable(loc, tts))
{
supportedLocales.add(loc);
}
}
return supportedLocales;
}
private static boolean isLanguageAvailable(Locale language, TextToSpeech tts)
{
boolean available = false;
switch (tts.isLanguageAvailable(language))
{
case TextToSpeech.LANG_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
available = true;
break;
case TextToSpeech.LANG_MISSING_DATA:
case TextToSpeech.LANG_NOT_SUPPORTED:
available = false;
break;
}
return available;
}
public static String logOnActivityResultDataCheck(int requestCode, int resultCode, Intent data)
{
StringBuilder sb = new StringBuilder();
if (requestCode == CommonTtsMethods.SPEECH_DATA_CHECK_CODE)
{
sb.append("data status: ").append(NEW_LINE);
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
sb.append("pass").append(NEW_LINE);
// success, create the TTS instance
Log.d(TAG, "has it");
} else
{
sb.append("fail").append(NEW_LINE);
}
//
sb.append("extra info:").append(NEW_LINE);
if (data.hasExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES))
{
List<String> voices = data
.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_AVAILABLE_VOICES);
sb.append("available voices: ").append(NEW_LINE);
for (String voice : voices)
{
sb.append(voice).append(NEW_LINE);
}
}
if (data.hasExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES))
{
//does this come back when you try to specify a crazy voice???
List<String> dataFiles = data
.getStringArrayListExtra(TextToSpeech.Engine.EXTRA_UNAVAILABLE_VOICES);
sb.append("unavailable voices: ").append(NEW_LINE);
for (String dataFile : dataFiles)
{
sb.append(dataFile).append(NEW_LINE);
}
}
sb.append(NEW_LINE);
if (data.hasExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_ROOT_DIRECTORY))
{
String rootDir = data
.getStringExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_ROOT_DIRECTORY);
if (rootDir == null)
{
sb.append("data root directory unknown ").append(NEW_LINE);
}
else
{
sb.append("data root directory: ").append(NEW_LINE);
sb.append(rootDir).append(NEW_LINE);
}
}
if (data.hasExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_FILES))
{
String [] dataFiles = data
.getStringArrayExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_FILES);
if (dataFiles == null)
{
sb.append("data files unknown").append(NEW_LINE);
} else
{
sb.append("data files: ").append(NEW_LINE);
for (String dataFile : dataFiles)
{
sb.append(dataFile)
.append(NEW_LINE);
}
}
}
if (data.hasExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_FILES_INFO))
{
String[] info = data
.getStringArrayExtra(TextToSpeech.Engine.EXTRA_VOICE_DATA_FILES_INFO);
if (info == null)
{
sb.append("data files info unknown").append(NEW_LINE);
} else
{
sb.append("data files info: ").append(NEW_LINE);
for (String dataFile : info)
{
sb.append(dataFile)
.append(NEW_LINE);
}
}
}
sb.append("Intent.toString():").append(NEW_LINE);
Object result = data.getExtras();
sb.append(result.toString()).append(NEW_LINE);
}
return sb.toString();
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.tts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.speech.tts.TextToSpeech;
import android.util.Log;
/**
* helps track the status of downloading the language data when the app requires
* it. It stores the status in a SharedPreferences field. Apps should check its
* current value by using the static methods.
*
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class LanguageDataInstallBroadcastReceiver extends BroadcastReceiver
{
private static final String TAG = "LanguageDataInstallBroadcastReceiver";
private static final String PREFERENCES_NAME = "installedLanguageData";
private static final String WAITING_PREFERENCE_NAME =
"WAITING_PREFERENCE_NAME";
private static final Boolean WAITING_DEFAULT = false;
public LanguageDataInstallBroadcastReceiver()
{
}
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(
TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED))
{
Log.d(TAG, "language data preference: " + intent.getAction());
// clear waiting state
setWaiting(context, false);
}
}
/**
* check if the receiver is waiting for a language data install
*/
public static boolean isWaiting(Context context)
{
SharedPreferences preferences;
preferences =
context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_WORLD_READABLE);
boolean waiting =
preferences
.getBoolean(WAITING_PREFERENCE_NAME, WAITING_DEFAULT);
return waiting;
}
/**
* start waiting by setting a flag
*/
public static void setWaiting(Context context, boolean waitingStatus)
{
SharedPreferences preferences;
preferences =
context.getSharedPreferences(PREFERENCES_NAME,
Context.MODE_WORLD_WRITEABLE);
Editor editor = preferences.edit();
editor.putBoolean(WAITING_PREFERENCE_NAME, waitingStatus);
editor.commit();
}
}
// /**
// * register this receiver, calling this method is only necessary if you
// * didn't create the receiver via the manifest
// *
// * @param context
// */
// public void register(Context context)
// {
// Log.d(TAG, "registered a receiver!!");
// context.registerReceiver(this, new IntentFilter(
// TextToSpeech.Engine.ACTION_TTS_DATA_INSTALLED));
// }
//
// /**
// * unregister itself, also clear the shared preference
// */
// public void unregister(Context context)
// {
// context.unregisterReceiver(this);
// }
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.text.match;
/**
* encode strings using soundex, but allow partial matches
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class SoundsLikeThresholdWordMatcher extends SoundsLikeWordMatcher
{
private int minimumCharactersSame;
public SoundsLikeThresholdWordMatcher(int minimumCharactersSame,
String... wordsIn)
{
super(wordsIn);
this.minimumCharactersSame = minimumCharactersSame;
}
@Override
public boolean isIn(String wordCheck)
{
boolean in = false;
String compareTo = soundex.encode(wordCheck);
for (String word : getWords())
{
if (sameEncodedString(word, compareTo))
{
in = true;
break;
}
}
return in;
}
private boolean sameEncodedString(String s1, String s2)
{
int numSame = 0;
for (int i = 0; i < s1.length(); i++)
{
char c1 = s1.charAt(i);
char c2 = s2.charAt(i);
if (c1 == c2)
{
numSame++;
}
}
return (numSame >= minimumCharactersSame);
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.text.match;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/**
* Match incoming words to a set of words, sublasses may encode the strings first
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class WordMatcher
{
private Set<String> words;
public static final int NOT_IN = -1;
public WordMatcher(String... wordsIn)
{
this(Arrays.asList(wordsIn));
}
public WordMatcher(List<String> wordsIn)
{
//care about order so we can execute isInAt
words = new LinkedHashSet<String>(wordsIn);
}
public Set<String> getWords()
{
return words;
}
public boolean isIn(String word)
{
return words.contains(word);
}
public boolean isIn(String [] wordsIn)
{
boolean wordIn = false;
for (String word : wordsIn)
{
if (isIn(word))
{
wordIn = true;
break;
}
}
return wordIn;
}
public int isInAt(String [] wordsIn)
{
int which = NOT_IN;
for (String word : wordsIn)
{
which = isInAt(word);
if (which != NOT_IN)
{
break;
}
}
return which;
}
public int isInAt(String wordCheck)
{
int which = NOT_IN;
int ct = 0;
for (String word : words)
{
if (word.equals(wordCheck))
{
which = ct;
break;
}
ct++;
}
return which;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
for (String word : getWords())
{
sb.append(word).append(" ");
}
return sb.toString().trim();
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.text.match;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.codec.language.Soundex;
/**
* encode strings using soundex
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class SoundsLikeWordMatcher extends WordMatcher
{
protected static Soundex soundex;
static
{
soundex = new Soundex();
}
public SoundsLikeWordMatcher(String... wordsIn)
{
this(Arrays.asList(wordsIn));
}
public SoundsLikeWordMatcher(List<String> wordsIn)
{
super(encode(wordsIn));
}
@Override
public boolean isIn(String word)
{
return super.isIn(encode(word));
}
protected static List<String> encode(List<String> input)
{
List<String> encoded = new ArrayList<String>();
for (String in : input)
{
encoded.add(encode(in));
}
return encoded;
}
private static String encode(String in)
{
String encoded = in;
try
{
encoded = soundex.encode(in);
}
catch (IllegalArgumentException e)
{
//for weird characters that soundex doesn't understand
}
return encoded;
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.text;
/**
* utility class for processing recognition results
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class WordList
{
private String [] words;
private String source;
public WordList(String source)
{
this.source = source.toLowerCase();
words = this.source.split("\\s");
}
public String getStringAfter(int wordIndex)
{
int startAt = wordIndex + 1;
if (startAt >= words.length)
{
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = startAt; i < words.length; i++)
{
sb.append(words[i]).append(" ");
}
return sb.toString();
}
public String getStringWithout(int indexToRemove)
{
if (indexToRemove >= words.length)
{
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++)
{
if (i != indexToRemove)
{
sb.append(words[i]).append(" ");
}
}
return sb.toString();
}
public String[] getWords()
{
return words;
}
/**
* @return the source
*/
public String getSource()
{
return source;
}
/**
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return source;
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
/**
* abstract class for getting speech, handles some boiler plate code. Any
* Activity that uses speech should extend this, or utilize the methods in
* {@link SpeechRecognitionUtil}
*
* @author gmilette
*/
public abstract class SpeechRecognizingActivity extends Activity implements
RecognitionListener
{
private static final String TAG = "SpeechRecognizingActivity";
/**
* code to identify return recognition results
*/
public static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
public static final int UNKNOWN_ERROR = -1;
private SpeechRecognizer recognizer;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
boolean recognizerIntent =
SpeechRecognitionUtil.isSpeechAvailable(this);
if (!recognizerIntent)
{
speechNotAvailable();
}
boolean direct = SpeechRecognizer.isRecognitionAvailable(this);
if (!direct)
{
directSpeechNotAvailable();
}
}
protected void checkForLanguage(final Locale language)
{
OnLanguageDetailsListener andThen = new OnLanguageDetailsListener()
{
@Override
public void onLanguageDetailsReceived(LanguageDetailsChecker data)
{
// do a best match
String languageToUse = data.matchLanguage(language);
languageCheckResult(languageToUse);
}
};
SpeechRecognitionUtil.getLanguageDetails(this, andThen);
}
/**
* execute the RecognizerIntent, then call
* {@link #receiveWhatWasHeard(List, List)} when done
*/
public void recognize(Intent recognizerIntent)
{
startActivityForResult(recognizerIntent,
VOICE_RECOGNITION_REQUEST_CODE);
}
/**
* Handle the results from the RecognizerIntent.
*/
@Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == VOICE_RECOGNITION_REQUEST_CODE)
{
if (resultCode == RESULT_OK)
{
List<String> heard =
data.
getStringArrayListExtra
(RecognizerIntent.EXTRA_RESULTS);
float[] scores =
data.
getFloatArrayExtra
(RecognizerIntent.EXTRA_CONFIDENCE_SCORES);
if (scores == null)
{
for (int i = 0; i < heard.size(); i++)
{
Log.d(TAG, i + ": " + heard.get(i));
}
}
else
{
for (int i = 0; i < heard.size(); i++)
{
Log.d(TAG, i + ": " + heard.get(i) + " score: "
+ scores[i]);
}
}
receiveWhatWasHeard(heard, scores);
}
else
{
Log.d(TAG, "error code: " + resultCode);
recognitionFailure(UNKNOWN_ERROR);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* called when speech is not available on this device, and when
* {@link #recognize(Intent)} will not work
*/
abstract protected void speechNotAvailable();
/**
* called when {@link SpeechRecognizer} cannot be used on this device and
* {@link #recognizeDirectly(Intent)} will not work
*/
abstract protected void directSpeechNotAvailable();
/**
* call back the result from {@link #checkForLanguage(Locale)}
*
* @param languageToUse
* the language string to use or null if failure
*/
abstract protected void languageCheckResult(String languageToUse);
/**
* result of speech recognition
*
* @param heard
* possible speech to text conversions
* @param confidenceScores
* the confidence for the strings in heard
*/
abstract protected void receiveWhatWasHeard(List<String> heard,
float[] confidenceScores);
/**
* @param code
* If using {@link #recognizeDirectly(Intent) it will be
* the error code from {@link SpeechRecognizer}
* if using {@link #recognize(Intent)}
* it will be {@link #UNKNOWN_ERROR}.
*/
abstract protected void recognitionFailure(int errorCode);
//direct speech recognition methods follow
/**
* Uses {@link SpeechRecognizer} to perform recognition and then calls
* {@link #receiveWhatWasHeard(List, float[])} with the results <br>
* check {@link SpeechRecognizer.isRecognitionAvailable(context)} before
* calling this method otherwise if it isn't available the code will report
* an error
*/
public void recognizeDirectly(Intent recognizerIntent)
{
// SpeechRecognizer requires EXTRA_CALLING_PACKAGE, so add if it's not
// here
if (!recognizerIntent.hasExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE))
{
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
"com.dummy");
}
SpeechRecognizer recognizer = getSpeechRecognizer();
recognizer.startListening(recognizerIntent);
}
@Override
public void onResults(Bundle results)
{
Log.d(TAG, "full results");
receiveResults(results);
}
@Override
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "partial results");
receiveResults(partialResults);
}
/**
* common method to process any results bundle from {@link SpeechRecognizer}
*/
private void receiveResults(Bundle results)
{
if ((results != null)
&& results.containsKey(SpeechRecognizer.RESULTS_RECOGNITION))
{
List<String> heard =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
float[] scores =
results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
receiveWhatWasHeard(heard, scores);
}
}
@Override
public void onError(int errorCode)
{
recognitionFailure(errorCode);
}
/**
* stop the speech recognizer
*/
@Override
protected void onPause()
{
if (getSpeechRecognizer() != null)
{
getSpeechRecognizer().stopListening();
getSpeechRecognizer().cancel();
getSpeechRecognizer().destroy();
}
super.onPause();
}
/**
* lazy initialize the speech recognizer
*/
private SpeechRecognizer getSpeechRecognizer()
{
if (recognizer == null)
{
recognizer = SpeechRecognizer.createSpeechRecognizer(this);
recognizer.setRecognitionListener(this);
}
return recognizer;
}
// other unused methods from RecognitionListener...
@Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "ready for speech " + params);
}
@Override
public void onEndOfSpeech()
{
}
/**
* @see android.speech.RecognitionListener#onBeginningOfSpeech()
*/
@Override
public void onBeginningOfSpeech()
{
}
@Override
public void onBufferReceived(byte[] buffer)
{
}
@Override
public void onRmsChanged(float rmsdB)
{
}
@Override
public void onEvent(int eventType, Bundle params)
{
}
public void onPartialResultsUnsupported(Bundle partialResults)
{
Log.d(TAG, "partial results");
if (partialResults
.containsKey(SpeechRecognitionUtil.UNSUPPORTED_GOOGLE_RESULTS))
{
String[] heard =
partialResults
.getStringArray(SpeechRecognitionUtil.UNSUPPORTED_GOOGLE_RESULTS);
float[] scores =
partialResults
.getFloatArray(SpeechRecognitionUtil.UNSUPPORTED_GOOGLE_RESULTS_CONFIDENCE);
receiveWhatWasHeard(Arrays.asList(heard), scores);
}
else
{
receiveResults(partialResults);
}
}
} | Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.Date;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.SpeechRecognizer;
import android.util.Log;
/**
* just logs what it receives from the {@link SpeechRecognizer} useful for testing
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class LoggingRecognitionListener implements RecognitionListener
{
private static final String TAG = "LoggingRecognitionListener";
private SpeechRecognizer recognizer;
public LoggingRecognitionListener(SpeechRecognizer recognizer)
{
this.recognizer = recognizer;
}
@Override
public void onRmsChanged(float rmsdB)
{
// Log.d(TAG, "rmsdB " + rmsdB);
}
@Override
public void onResults(Bundle results)
{
logResults(results);
}
@Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "params " + params);
}
@Override
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "partial results");
logResults(partialResults);
}
@Override
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "eventType " + eventType);
}
@Override
public void onError(int error)
{
Log.d(TAG, "error " + error);
}
@Override
public void onEndOfSpeech()
{
Log.d(TAG, "onEndOfSpeech " + new Date().toLocaleString());
//should it stop now?
recognizer.stopListening();
recognizer.destroy();
}
@Override
public void onBufferReceived(byte[] buffer)
{
// Log.d(TAG, "buffer " + buffer.length);
}
@Override
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech " + new Date().toLocaleString());
}
private void logResults(Bundle bundle)
{
if (bundle != null)
{
Log.d(TAG, "bundle: " + bundle.toString());
}
if ((bundle != null)
&& bundle.containsKey(SpeechRecognizer.RESULTS_RECOGNITION))
{
int i = 0;
for (String result : bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION))
{
Log.d(TAG, i + ": " + result);
i++;
}
}
}
} | Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
/**
* A utility class to perform common speech recognition functions
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class SpeechRecognitionUtil
{
private static final String TAG = "SpeechRecognitionUtil";
//Note: Google seems to send back these values
//use at your own risk
public static final String UNSUPPORTED_GOOGLE_RESULTS_CONFIDENCE = "com.google.android.voicesearch.UNSUPPORTED_PARTIAL_RESULTS_CONFIDENCE";
public static final String UNSUPPORTED_GOOGLE_RESULTS = "com.google.android.voicesearch.UNSUPPORTED_PARTIAL_RESULTS";
/**
* checks if the device supports speech recognition
* at all
*/
public static boolean isSpeechAvailable(Context context)
{
PackageManager pm = context.getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
boolean available = true;
if (activities.size() == 0)
{
available = false;
}
return available;
//also works, but it is checking something slightly different
//it checks for the recognizer service. so we use the above check
//instead since it directly answers the question of whether or not
//the app can service the intent the app will send
// return SpeechRecognizer.isRecognitionAvailable(context);
}
/**
* collects language details and returns result to andThen
*/
public static void getLanguageDetails(Context context,
OnLanguageDetailsListener andThen)
{
Intent detailsIntent = new Intent(
RecognizerIntent.ACTION_GET_LANGUAGE_DETAILS);
LanguageDetailsChecker checker = new LanguageDetailsChecker(andThen);
context.sendOrderedBroadcast(detailsIntent, null, checker, null,
Activity.RESULT_OK, null, null);
//also works
// Intent detailsIntent = RecognizerIntent.getVoiceDetailsIntent(this);
}
public static List<String> getHeardFromDirect(Bundle bundle)
{
List<String> results = new ArrayList<String>();
if ((bundle != null)
&& bundle.containsKey(SpeechRecognizer.RESULTS_RECOGNITION))
{
results =
bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
}
return results;
}
public static float[] getConfidenceFromDirect(Bundle bundle)
{
float [] scores = null;
if ((bundle != null)
&& bundle.containsKey(SpeechRecognizer.RESULTS_RECOGNITION))
{
scores =
bundle.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
}
return scores;
}
public static List<String> getHeardFromDirectPartial(Bundle bundle)
{
List<String> results = new ArrayList<String>();
if (bundle.containsKey(UNSUPPORTED_GOOGLE_RESULTS))
{
String [] resultsArray =
bundle.getStringArray(UNSUPPORTED_GOOGLE_RESULTS);
results = Arrays.asList(resultsArray);
}
else
{
return getHeardFromDirect(bundle);
}
return results;
}
public static float[] getConfidenceFromDirectPartial(Bundle bundle)
{
float[] scores = null;
if (bundle
.containsKey(UNSUPPORTED_GOOGLE_RESULTS_CONFIDENCE))
{
scores =
bundle.getFloatArray(UNSUPPORTED_GOOGLE_RESULTS_CONFIDENCE);
}
else
{
scores = getConfidenceFromDirect(bundle);
}
return scores;
}
public static void recognizeSpeechDirectly(Context context,
Intent recognizerIntent, RecognitionListener listener,
SpeechRecognizer recognizer)
{
//need to have a calling package for it to work
if (!recognizerIntent.hasExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE))
{
recognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, "com.dummy");
}
recognizer.setRecognitionListener(listener);
recognizer.startListening(recognizerIntent);
}
public static String diagnoseErrorCode(int errorCode)
{
String message;
switch (errorCode)
{
case SpeechRecognizer.ERROR_AUDIO:
message = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
message = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
message = "Insufficient permissions";
break;
case SpeechRecognizer.ERROR_NETWORK:
message = "Network error";
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
message = "Network timeout";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
message = "No match";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
message = "RecognitionService busy";
break;
case SpeechRecognizer.ERROR_SERVER:
message = "error from server";
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
message = "No speech input";
break;
default:
message = "Didn't understand, please try again.";
break;
}
return message;
}
} | Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech;
import java.util.Locale;
import root.gast.speech.tts.TextToSpeechInitializer;
import root.gast.speech.tts.TextToSpeechStartupListener;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.UtteranceProgressListener;
import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener;
import android.util.Log;
/**
* handy {@link Activity} that handles setting up both tts and speech for easy re-use
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public abstract class SpeechRecognizingAndSpeakingActivity extends
SpeechRecognizingActivity implements TextToSpeechStartupListener
{
private static final String TAG = "SpeechRecognizingAndSpeakingActivity";
private TextToSpeechInitializer ttsInit;
private TextToSpeech tts;
/**
* @see root.gast.speech.SpeechRecognizingActivity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
init();
}
private void init()
{
deactivateUi();
ttsInit = new TextToSpeechInitializer(this, Locale.getDefault(), this);
}
@Override
public void onSuccessfulInit(TextToSpeech tts)
{
Log.d(TAG, "successful init");
this.tts = tts;
activateUi();
setTtsListener();
}
private void setTtsListener()
{
final SpeechRecognizingAndSpeakingActivity callWithResult = this;
if (Build.VERSION.SDK_INT >= 15)
{
int listenerResult = tts.setOnUtteranceProgressListener(new UtteranceProgressListener()
{
@Override
public void onDone(String utteranceId)
{
callWithResult.onDone(utteranceId);
}
@Override
public void onError(String utteranceId)
{
callWithResult.onError(utteranceId);
}
@Override
public void onStart(String utteranceId)
{
callWithResult.onStart(utteranceId);
}
});
if (listenerResult != TextToSpeech.SUCCESS)
{
Log.e(TAG, "failed to add utterance progress listener");
}
}
else
{
int listenerResult = tts.setOnUtteranceCompletedListener(new OnUtteranceCompletedListener()
{
@Override
public void onUtteranceCompleted(String utteranceId)
{
callWithResult.onDone(utteranceId);
}
});
if (listenerResult != TextToSpeech.SUCCESS)
{
Log.e(TAG, "failed to add utterance completed listener");
}
}
}
//sub class may override these, otherwise, one or the other
//will occur depending on the Android version
public void onDone(String utteranceId)
{
}
public void onError(String utteranceId)
{
}
public void onStart(String utteranceId)
{
}
@Override
public void onFailedToInit()
{
DialogInterface.OnClickListener onClickOk = makeOnFailedToInitHandler();
AlertDialog a = new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage("Unable to create text to speech")
.setNeutralButton("Ok", onClickOk).create();
a.show();
}
@Override
public void onRequireLanguageData()
{
DialogInterface.OnClickListener onClickOk = makeOnClickInstallDialogListener();
DialogInterface.OnClickListener onClickCancel = makeOnFailedToInitHandler();
AlertDialog a = new AlertDialog.Builder(this).setTitle(
"Error")
.setMessage("Requires Language data to proceed, would you like to install?")
.setPositiveButton("Ok", onClickOk)
.setNegativeButton("Cancel", onClickCancel).create();
a.show();
}
@Override
public void onWaitingForLanguageData()
{
//either wait for install
DialogInterface.OnClickListener onClickWait = makeOnFailedToInitHandler();
DialogInterface.OnClickListener onClickInstall = makeOnClickInstallDialogListener();
AlertDialog a = new AlertDialog.Builder(this)
.setTitle("Info")
.setMessage(
"Please wait for the language data to finish installing and try again.")
.setNegativeButton("Wait", onClickWait)
.setPositiveButton("Retry", onClickInstall).create();
a.show();
}
private DialogInterface.OnClickListener makeOnClickInstallDialogListener()
{
return new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
ttsInit.installLanguageData();
}
};
}
private DialogInterface.OnClickListener makeOnFailedToInitHandler()
{
return new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
finish();
}
};
}
//override in subclass
protected void deactivateUi()
{
Log.d(TAG, "deactivate ui");
}
protected void activateUi()
{
Log.d(TAG, "activate ui");
}
@Override
protected void speechNotAvailable()
{
DialogInterface.OnClickListener onClickOk = makeOnFailedToInitHandler();
AlertDialog a =
new AlertDialog.Builder(this)
.setTitle("Error")
.setMessage(
"This device does not support speech recognition. Click ok to quit.")
.setPositiveButton("Ok", onClickOk).create();
a.show();
}
@Override
protected void directSpeechNotAvailable()
{
//do nothing
}
protected void languageCheckResult(String languageToUse)
{
// not used
}
protected void recognitionFailure(int errorCode)
{
String message = SpeechRecognitionUtil.diagnoseErrorCode(errorCode);
Log.d(TAG, "speech error: " + message);
}
protected TextToSpeech getTts()
{
return tts;
}
@Override
protected void onDestroy()
{
if (getTts() != null)
{
getTts().shutdown();
}
super.onDestroy();
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
/**
* receive results from a {@link SpeechActivator}
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public interface SpeechActivationListener
{
public void activated(boolean success);
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public interface SpeechActivator
{
/**
* listen for speech activation, when heard, call a {@link SpeechActivationListener}
* and stop listening
*/
public void detectActivation();
/**
* stop waiting for activation.
*/
public void stop();
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
/**
* Persistently run a speech activator in the background.
* Use {@link Intent}s to start and stop it
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class SpeechActivationService extends Service implements
SpeechActivationListener
{
private static final String TAG = "SpeechActivationService";
public static final String ACTIVATION_TYPE_INTENT_KEY =
"ACTIVATION_TYPE_INTENT_KEY";
public static final String ACTIVATION_RESULT_INTENT_KEY =
"ACTIVATION_RESULT_INTENT_KEY";
public static final String ACTIVATION_RESULT_BROADCAST_NAME =
"root.gast.playground.speech.ACTIVATION";
/**
* send this when external code wants the Service to stop
*/
public static final String ACTIVATION_STOP_INTENT_KEY =
"ACTIVATION_STOP_INTENT_KEY";
public static final int NOTIFICATION_ID = 10298;
private boolean isStarted;
private SpeechActivator activator;
@Override
public void onCreate()
{
super.onCreate();
isStarted = false;
}
public static Intent makeStartServiceIntent(Context context,
String activationType,int delay)
{
Log.d(TAG,"makeServiceIntent started");
if(delay > 0){
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Intent i = new Intent(context, SpeechActivationService.class);
i.putExtra(ACTIVATION_TYPE_INTENT_KEY, activationType);
return i;
}
public static Intent makeServiceStopIntent(Context context)
{
Intent i = new Intent(context, SpeechActivationService.class);
i.putExtra(ACTIVATION_STOP_INTENT_KEY, true);
return i;
}
/**
* stop or start an activator based on the activator type and if an
* activator is currently running
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent != null)
{
if (intent.hasExtra(ACTIVATION_STOP_INTENT_KEY))
{
Log.d(TAG, "stop service intent");
activated(false);
}
else
{
if (isStarted)
{
// the activator is currently started
// if the intent is requesting a new activator
// stop the current activator and start
// the new one
if (isDifferentType(intent))
{
Log.d(TAG, "is differnet type");
stopActivator();
startDetecting(intent);
}
else
{
Log.d(TAG, "already started this type");
}
}
else
{
// activator not started, start it
startDetecting(intent);
}
}
}
// restart in case the Service gets canceled
return START_REDELIVER_INTENT;
}
private void startDetecting(Intent intent)
{
activator = getRequestedActivator(intent);
Log.d(TAG, "started: " + activator.getClass().getSimpleName());
isStarted = true;
activator.detectActivation();
//startForeground(NOTIFICATION_ID, getNotification());
}
private SpeechActivator getRequestedActivator(Intent intent)
{
String type = intent.getStringExtra(ACTIVATION_TYPE_INTENT_KEY);
// create based on a type name
SpeechActivator speechActivator =
SpeechActivatorFactory.createSpeechActivator(this, this, type);
return speechActivator;
}
/**
* determine if the intent contains an activator type
* that is different than the currently running type
*/
private boolean isDifferentType(Intent intent)
{
boolean different = false;
if (activator == null)
{
return true;
}
else
{
SpeechActivator possibleOther = getRequestedActivator(intent);
different = !(possibleOther.getClass().getName().
equals(activator.getClass().getName()));
}
return different;
}
@Override
public void activated(boolean success)
{
// make sure the activator is stopped before doing anything else
stopActivator();
// broadcast result
Intent intent = new Intent(ACTIVATION_RESULT_BROADCAST_NAME);
intent.putExtra(ACTIVATION_RESULT_INTENT_KEY, success);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK, "My wakelook");
// This will make the screen and power stay on
// This will release the wakelook after 1000 ms
wakeLock.acquire(1000);
// Alternative you can request and / or release the wakelook via:
// wakeLock.acquire(); wakeLock.release();
sendBroadcast(intent);
// always stop after receive an activation
stopSelf();
}
@Override
public void onDestroy()
{
Log.d(TAG, "On destroy");
super.onDestroy();
stopActivator();
stopForeground(true);
}
private void stopActivator()
{
if (activator != null)
{
Log.d(TAG, "stopped: " + activator.getClass().getSimpleName());
activator.stop();
isStarted = false;
}
}
// @SuppressLint("NewApi")
// private Notification getNotification()
// {
// // determine label based on the class
// String name = SpeechActivatorFactory.getLabel(this, activator);
// String message ="Listening"
// + " " + name;
// String title = "ANNA";
//
// PendingIntent pi =
// PendingIntent.getService(this, 0, makeServiceStopIntent(this),
// 0);
//
// Notification notification = null;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
// {
// Notification.Builder builder = new Notification.Builder(this);
// builder.setWhen(System.currentTimeMillis()).setTicker(message)
// .setContentTitle(title).setContentText(message)
// .setContentIntent(pi);
// notification = builder.getNotification();
// }
//// else
//// {
//// notification =
//// new Notification(0,message,
//// System.currentTimeMillis());
//// notification.setLatestEventInfo(this, title, message, pi);
//// }
//
// return notification;
// }
@Override
public IBinder onBind(Intent intent)
{
return null;
}
} | Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import java.io.File;
import java.io.IOException;
import root.gast.audio.interp.SingleClapDetector;
import root.gast.audio.record.MaxAmplitudeRecorder;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
/**
* utility for executing speech activators who need to run something
* asyncronously
*
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class ClapperSpeechActivationTask extends AsyncTask<Void, Void, Boolean>
{
private static final String TAG = "ClapperSpeechActivationTask";
private SpeechActivationListener listener;
private Context context;
private static final String TEMP_AUDIO_DIRECTORY = "tempaudio";
/**
* time between amplitude checks
*/
private static final int CLIP_TIME = 1000;
public ClapperSpeechActivationTask(Context context,
SpeechActivationListener listener)
{
this.context = context;
this.listener = listener;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params)
{
boolean heard = detectClap();
return heard;
}
/**
* start detecting a clap, return when done
*/
private boolean detectClap()
{
SingleClapDetector clapper =
new SingleClapDetector(SingleClapDetector.AMPLITUDE_DIFF_MED);
Log.d(TAG, "recording amplitude");
String audioStorageDirectory =
context.getExternalFilesDir(TEMP_AUDIO_DIRECTORY)
+ File.separator + "audio.3gp";
// pass in this so recording can stop if this task is canceled
MaxAmplitudeRecorder recorder =
new MaxAmplitudeRecorder(CLIP_TIME, audioStorageDirectory,
clapper, this);
// start recording
boolean heard = false;
try
{
heard = recorder.startRecording();
} catch (IOException io)
{
Log.e(TAG, "failed to record", io);
heard = false;
} catch (IllegalStateException se)
{
Log.e(TAG, "failed to record, recorder not setup properly", se);
heard = false;
} catch (RuntimeException se)
{
Log.e(TAG, "failed to record, recorder already being used", se);
heard = false;
}
return heard;
}
@Override
protected void onPostExecute(Boolean result)
{
listener.activated(result);
super.onPostExecute(result);
}
@Override
protected void onCancelled()
{
Log.d(TAG, "cancelled");
super.onCancelled();
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import android.content.Context;
import android.util.Log;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class ClapperActivator implements SpeechActivator
{
private static final String TAG = "ClapperActivator";
private ClapperSpeechActivationTask activeTask;
private SpeechActivationListener listener;
private Context context;
public ClapperActivator(Context context, SpeechActivationListener listener)
{
this.context = context;
this.listener = listener;
}
@Override
public void detectActivation()
{
Log.d(TAG, "started clapper activation");
activeTask = new ClapperSpeechActivationTask(context, listener);
activeTask.execute();
}
@Override
public void stop()
{
if (activeTask != null)
{
activeTask.cancel(true);
}
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import java.io.File;
import java.io.IOException;
import root.gast.audio.interp.SingleClapDetector;
import root.gast.audio.record.MaxAmplitudeRecorder;
import android.content.Context;
import android.util.Log;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class ClapperActivationExecutor implements SpeechActivator
{
private static final String TAG = "ClapperActivation";
/**
* time between amplitude checks
*/
private static final int CLIP_TIME = 1000;
private MaxAmplitudeRecorder recorder;
private Context context;
public ClapperActivationExecutor(Context context)
{
this.context = context;
}
@Override
public void detectActivation()
{
detectClap();
}
public boolean detectClap()
{
//start the task
SingleClapDetector clapper =
new SingleClapDetector(SingleClapDetector.AMPLITUDE_DIFF_MED);
Log.d(TAG, "recording amplitude");
String appStorageLocation =
context.getExternalFilesDir("type") + File.separator
+ "audio.3gp";
MaxAmplitudeRecorder recorder =
new MaxAmplitudeRecorder(CLIP_TIME, appStorageLocation,
clapper, null);
// start recording
boolean heard = false;
try
{
heard = recorder.startRecording();
} catch (IOException io)
{
Log.e(TAG, "failed to record", io);
heard = false;
} catch (IllegalStateException se)
{
Log.e(TAG, "failed to record, recorder not setup properly", se);
heard = false;
}
return heard;
}
public void stop()
{
if (recorder != null)
{
recorder.stopRecording();
}
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import java.util.List;
import root.gast.speech.SpeechRecognitionUtil;
import root.gast.speech.text.WordList;
import root.gast.speech.text.match.SoundsLikeWordMatcher;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
/**
* Uses direct speech recognition to activate when the user speaks
* one of the target words
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class WordActivator implements SpeechActivator, RecognitionListener
{
private static final String TAG = "WordActivator";
private Context context;
private SpeechRecognizer recognizer;
private SoundsLikeWordMatcher matcher;
private SpeechActivationListener resultListener;
public WordActivator(Context context,
SpeechActivationListener resultListener, String... targetWords)
{
this.context = context;
this.matcher = new SoundsLikeWordMatcher(targetWords);
this.resultListener = resultListener;
}
@Override
public void detectActivation()
{
recognizeSpeechDirectly();
}
private void recognizeSpeechDirectly()
{
Intent recognizerIntent =
new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH);
// accept partial results if they come
recognizerIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
SpeechRecognitionUtil.recognizeSpeechDirectly(context,
recognizerIntent, this, getSpeechRecognizer());
}
public void stop()
{
if (getSpeechRecognizer() != null)
{
getSpeechRecognizer().stopListening();
getSpeechRecognizer().cancel();
getSpeechRecognizer().destroy();
}
}
@Override
public void onResults(Bundle results)
{
Log.d(TAG, "full results");
receiveResults(results);
}
@Override
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "partial results");
receiveResults(partialResults);
}
/**
* common method to process any results bundle from {@link SpeechRecognizer}
*/
private void receiveResults(Bundle results)
{
if ((results != null)
&& results.containsKey(SpeechRecognizer.RESULTS_RECOGNITION))
{
List<String> heard =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
float[] scores =
results.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
receiveWhatWasHeard(heard, scores);
}
else
{
Log.d(TAG, "no results");
}
}
private void receiveWhatWasHeard(List<String> heard, float[] scores)
{
boolean heardTargetWord = false;
// find the target word
for (String possible : heard)
{
WordList wordList = new WordList(possible);
if (matcher.isIn(wordList.getWords()))
{
Log.d(TAG, "HEARD IT!");
heardTargetWord = true;
break;
}
}
if (heardTargetWord)
{
stop();
resultListener.activated(true);
}
else
{
// keep going
recognizeSpeechDirectly();
}
}
@Override
public void onError(int errorCode)
{
if ((errorCode == SpeechRecognizer.ERROR_NO_MATCH)
|| (errorCode == SpeechRecognizer.ERROR_SPEECH_TIMEOUT))
{
Log.d(TAG, "didn't recognize anything");
// keep going
recognizeSpeechDirectly();
}
else
{
Log.d(TAG,
"FAILED "
+ SpeechRecognitionUtil
.diagnoseErrorCode(errorCode));
}
}
/**
* lazy initialize the speech recognizer
*/
private SpeechRecognizer getSpeechRecognizer()
{
if (recognizer == null)
{
recognizer = SpeechRecognizer.createSpeechRecognizer(context);
}
return recognizer;
}
// other unused methods from RecognitionListener...
@Override
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "ready for speech " + params);
}
@Override
public void onEndOfSpeech()
{
}
/**
* @see android.speech.RecognitionListener#onBeginningOfSpeech()
*/
@Override
public void onBeginningOfSpeech()
{
}
@Override
public void onBufferReceived(byte[] buffer)
{
}
@Override
public void onRmsChanged(float rmsdB)
{
}
@Override
public void onEvent(int eventType, Bundle params)
{
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.speech.activation;
import android.content.Context;
/**
* help create {@link SpeechActivator}s based on a type from the resources
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class SpeechActivatorFactory
{
public static SpeechActivator createSpeechActivator(Context context,
SpeechActivationListener callback, String type)
{
SpeechActivator speechActivator = null;
if (type.equals("speech"))
{
speechActivator = null;
}
else if (type.equals("clapper"))
{
speechActivator = new ClapperActivator(context, callback);
}
else if (type.equals("word"))
{
speechActivator = new WordActivator(context, callback, "hello");
}
return speechActivator;
}
// public static String getLabel(Context context, SpeechActivator speechActivator)
// {
// String label = "";
// if (speechActivator == null)
// {
// label = "speech activation button";
// }
// else if (speechActivator instanceof WordActivator)
// {
// label = "WordActivator";
// }
// else if ((speechActivator instanceof ClapperActivator))
// {
// label = "ClapperActivator";
// }
// else
// {
// label = "speech activation button";
// }
// return label;
// }
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.interp;
import root.gast.audio.record.AmplitudeClipListener;
import android.util.Log;
/**
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class SingleClapDetector implements AmplitudeClipListener
{
private static final String TAG = "SingleClapDetector";
/**
* required loudness to determine it is a clap
*/
private int amplitudeThreshold;
/**
* requires a little of noise by the user to trigger, background noise may
* trigger it
*/
public static final int AMPLITUDE_DIFF_LOW = 10000;
public static final int AMPLITUDE_DIFF_MED = 18000;
/**
* requires a lot of noise by the user to trigger. background noise isn't
* likely to be this loud
*/
public static final int AMPLITUDE_DIFF_HIGH = 25000;
private static final int DEFAULT_AMPLITUDE_DIFF = AMPLITUDE_DIFF_MED;
public SingleClapDetector()
{
this(DEFAULT_AMPLITUDE_DIFF);
}
public SingleClapDetector(int amplitudeThreshold)
{
this.amplitudeThreshold = amplitudeThreshold;
}
@Override
public boolean heard(int maxAmplitude)
{
boolean clapDetected = false;
if (maxAmplitude >= amplitudeThreshold)
{
Log.d(TAG, "heard a clap");
clapDetected = true;
}
return clapDetected;
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.interp;
import java.util.LinkedList;
import android.util.Log;
import root.gast.audio.processing.ZeroCrossing;
import root.gast.audio.record.AudioClipListener;
import root.gast.audio.util.AudioUtil;
/**
* track a history of frequencies, and determine if a new frequency is within
* the range of the ones in the history
*
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class ConsistentFrequencyDetector implements AudioClipListener
{
private static final String TAG = "ConsistentFrequencyDetector";
private LinkedList<Integer> frequencyHistory;
private int rangeThreshold;
private int silenceThreshold;
public static final int DEFAULT_SILENCE_THRESHOLD = 2000;
private static final boolean DEBUG = false;
public ConsistentFrequencyDetector(int historySize, int rangeThreshold,
int silenceThreshold)
{
frequencyHistory = new LinkedList<Integer>();
// pre-fill so modification is easy
for (int i = 0; i < historySize; i++)
{
frequencyHistory.add(Integer.MAX_VALUE);
}
this.rangeThreshold = rangeThreshold;
this.silenceThreshold = silenceThreshold;
}
@Override
public boolean heard(short[] audioData, int sampleRate)
{
int frequency = ZeroCrossing.calculate(sampleRate, audioData);
frequencyHistory.addFirst(frequency);
// since history is always full, just remove the last
frequencyHistory.removeLast();
int range = calculateRange();
if (DEBUG)
{
Log.d(TAG, "range: " + range + " threshold " + rangeThreshold
+ " loud: " + AudioUtil.rootMeanSquared(audioData));
}
boolean heard = false;
if (range < rangeThreshold)
{
// only trigger it isn't silence
if (AudioUtil.rootMeanSquared(audioData) > silenceThreshold)
{
Log.d(TAG, "heard");
heard = true;
}
else
{
Log.d(TAG, "not loud enough");
}
}
return heard;
}
private int calculateRange()
{
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (Integer val : frequencyHistory)
{
if (val >= max)
{
max = val;
}
if (val < min)
{
min = val;
}
}
if (DEBUG)
{
StringBuilder sb = new StringBuilder();
for (Integer val : frequencyHistory)
{
sb.append(val).append(" ");
}
Log.d(TAG, sb.toString() + " [" + (max - min) + "]");
}
return max - min;
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.interp;
import root.gast.audio.record.AudioClipListener;
import android.util.Log;
/**
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class LoudNoiseDetector implements AudioClipListener
{
private static final String TAG = "LoudNoiseDetector";
private double volumeThreshold;
public static final int DEFAULT_LOUDNESS_THRESHOLD = 2000;
private static final boolean DEBUG = true;
public LoudNoiseDetector()
{
volumeThreshold = DEFAULT_LOUDNESS_THRESHOLD;
}
public LoudNoiseDetector(double volumeThreshold)
{
this.volumeThreshold = volumeThreshold;
}
@Override
public boolean heard(short[] data, int sampleRate)
{
boolean heard = false;
// use rms to take the entire audio signal into account
// and discount any one single high amplitude
double currentVolume = rootMeanSquared(data);
if (DEBUG)
{
Log.d(TAG, "current: " + currentVolume + " threshold: "
+ volumeThreshold);
}
if (currentVolume > volumeThreshold)
{
Log.d(TAG, "heard");
heard = true;
}
return heard;
}
private double rootMeanSquared(short[] nums)
{
double ms = 0;
for (int i = 0; i < nums.length; i++)
{
ms += nums[i] * nums[i];
}
ms /= nums.length;
return Math.sqrt(ms);
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.interp;
import root.gast.audio.record.AudioClipListener;
import android.util.Log;
/**
* alternative Loud Noise detector that tracks the difference between
* the new noise and an averagre value. It might be useful in some situations.
* @author Greg Milette <<a
* href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public class LoudNoiseDetectorAboveNormal implements AudioClipListener
{
private static final String TAG = "MultipleClapDetector";
private double averageVolume;
private double lowPassAlpha = 0.5;
private double STARTING_AVERAGE = 100.0;
private double INCREASE_FACTOR = 100.0;
private static final boolean DEBUG = true;
public LoudNoiseDetectorAboveNormal()
{
averageVolume = STARTING_AVERAGE;
}
@Override
public boolean heard(short[] data, int sampleRate)
{
boolean heard = false;
// use rms to take the entire audio signal into account
// and discount any one single high amplitude
double currentVolume = rootMeanSquared(data);
double volumeThreshold = averageVolume * INCREASE_FACTOR;
if (DEBUG)
{
Log.d(TAG, "current: " + currentVolume + " avg: " + averageVolume
+ " threshold: " + volumeThreshold);
}
if (currentVolume > volumeThreshold)
{
Log.d(TAG, "heard");
heard = true;
}
else
{
// Big changes should have very little affect on
// the average value but if the average volume does increase
// consistently let the average increase too
averageVolume = lowPass(currentVolume, averageVolume);
}
return heard;
}
private double lowPass(double current, double last)
{
return last * (1.0 - lowPassAlpha) + current * lowPassAlpha;
}
private double rootMeanSquared(short[] nums)
{
double ms = 0;
for (int i = 0; i < nums.length; i++)
{
ms += nums[i] * nums[i];
}
ms /= nums.length;
return Math.sqrt(ms);
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.processing;
/**
* Calculates zero crossings to estimate frequency
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class ZeroCrossing
{
private static final String TAG = "ZeroCrossing.java";
/**
* calculate frequency using zero crossings
*/
public static int calculate(int sampleRate, short [] audioData)
{
int numSamples = audioData.length;
int numCrossing = 0;
for (int p = 0; p < numSamples-1; p++)
{
if ((audioData[p] > 0 && audioData[p + 1] <= 0) ||
(audioData[p] < 0 && audioData[p + 1] >= 0))
{
numCrossing++;
}
}
float numSecondsRecorded = (float)numSamples/(float)sampleRate;
float numCycles = numCrossing/2;
float frequency = numCycles/numSecondsRecorded;
return (int)frequency;
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.record;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public interface AmplitudeClipListener
{
/**
* return true if recording should stop
*/
public boolean heard(int maxAmplitude);
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.record;
import java.util.List;
/**
* allow many listeners to receive the data, but only one to act on it
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class OneDetectorManyObservers implements AudioClipListener
{
private AudioClipListener detector;
private List<AudioClipListener> observers;
public OneDetectorManyObservers(AudioClipListener detector, List<AudioClipListener> observers)
{
this.detector = detector;
this.observers = observers;
}
@Override
public boolean heard(short[] audioData, int sampleRate)
{
for (AudioClipListener observer : observers)
{
observer.heard(audioData, sampleRate);
}
return detector.heard(audioData, sampleRate);
}
}
| Java |
package root.gast.audio.record;
import java.io.IOException;
import root.gast.audio.util.AudioUtil;
import root.gast.audio.util.RecorderErrorLoggerListener;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.util.Log;
/**
* Records {@link MediaRecorder#getMaxAmplitude()}
* @author gmilette
*
*/
public class MaxAmplitudeRecorder
{
private static final String TAG = "MaxAmplitudeRecorder";
private static final long DEFAULT_CLIP_TIME = 1000;
private long clipTime = DEFAULT_CLIP_TIME;
private AmplitudeClipListener clipListener;
private boolean continueRecording;
private MediaRecorder recorder;
private String tmpAudioFile;
private AsyncTask task;
/**
*
* @param clipTime
* time to wait in between maxAmplitude checks
* @param tmpAudioFile
* should be a file where the MediaRecorder class can write
* temporary audio data
* @param clipListener
* called periodically to analyze the max amplitude
* @param task
* stop recording if this task is canceled
*/
public MaxAmplitudeRecorder(long clipTime, String tmpAudioFile,
AmplitudeClipListener clipListener, AsyncTask task)
{
this.clipTime = clipTime;
this.clipListener = clipListener;
this.tmpAudioFile = tmpAudioFile;
this.task = task;
}
/**
* start recording maximum amplitude and passing it to the
* {@link #clipListener} <br>
* @throws {@link IllegalStateException} if there is trouble creating
* the recorder
* @throws {@link IOException} if the SD card is not available
* @throws {@link RuntimeException} if audio recording channel is occupied
* @return true if {@link #clipListener} succeeded in detecting something
* false if it failed or the recording stopped for some other reason
*/
public boolean startRecording() throws IOException
{
Log.d(TAG, "recording maxAmplitude");
recorder = AudioUtil.prepareRecorder(tmpAudioFile);
// when an error occurs just stop recording
recorder.setOnErrorListener(new MediaRecorder.OnErrorListener()
{
@Override
public void onError(MediaRecorder mr, int what, int extra)
{
// log it
new RecorderErrorLoggerListener().onError(mr, what, extra);
// stop recording
stopRecording();
}
});
//possible RuntimeException if Audio recording channel is occupied
recorder.start();
continueRecording = true;
boolean heard = false;
recorder.getMaxAmplitude();
while (continueRecording)
{
Log.d(TAG, "waiting while recording...");
waitClipTime();
if (task != null)
{
Log.d(TAG, "continue recording: " + continueRecording + " cancelled after waiting? " + task.isCancelled());
}
//in case external code stopped this while read was happening
if ((!continueRecording) || ((task != null) && task.isCancelled()))
{
break;
}
int maxAmplitude = recorder.getMaxAmplitude();
Log.d(TAG, "current max amplitude: " + maxAmplitude);
heard = clipListener.heard(maxAmplitude);
if (heard)
{
stopRecording();
}
}
Log.d(TAG, "stopped recording max amplitude");
done();
return heard;
}
private void waitClipTime()
{
try
{
Thread.sleep(clipTime);
} catch (InterruptedException e)
{
Log.d(TAG, "interrupted");
}
}
/**
* stop recorder and clean up resources
*/
public void done()
{
Log.d(TAG, "stop recording on done");
if (recorder != null)
{
try
{
recorder.stop();
} catch (Exception e)
{
Log.d(TAG, "failed to stop");
return;
}
recorder.release();
}
}
public boolean isRecording()
{
return continueRecording;
}
public void stopRecording()
{
continueRecording = false;
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.record;
import java.util.List;
/**
* allow many listeners to receive the data, but only one to act on it
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class OneDetectorManyAmplitudeObservers implements AmplitudeClipListener
{
private AmplitudeClipListener detector;
private List<AmplitudeClipListener> observers;
public OneDetectorManyAmplitudeObservers(AmplitudeClipListener detector, List<AmplitudeClipListener> observers)
{
this.detector = detector;
this.observers = observers;
}
@Override
public boolean heard(int maxAmplitude)
{
for (AmplitudeClipListener observer : observers)
{
observer.heard(maxAmplitude);
}
return detector.heard(maxAmplitude);
}
}
| Java |
package root.gast.audio.record;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioRecord.OnRecordPositionUpdateListener;
import android.media.MediaRecorder.AudioSource;
import android.os.AsyncTask;
import android.util.Log;
/**
* record an audio clip and pass it to the listener
*
* @author gmilette
*
*/
public class AudioClipRecorder
{
private static final String TAG = "AudioClipRecorder";
private AudioRecord recorder;
private AudioClipListener clipListener;
/**
* state variable to control starting and stopping recording
*/
private boolean continueRecording;
public static final int RECORDER_SAMPLERATE_CD = 44100;
public static final int RECORDER_SAMPLERATE_8000 = 8000;
private static final int DEFAULT_BUFFER_INCREASE_FACTOR = 3;
private AsyncTask task;
private boolean heard;
public AudioClipRecorder(AudioClipListener clipListener)
{
this.clipListener = clipListener;
heard = false;
task = null;
}
public AudioClipRecorder(AudioClipListener clipListener, AsyncTask task)
{
this(clipListener);
this.task = task;
}
/**
* records with some default parameters
*/
public boolean startRecording()
{
return startRecording(RECORDER_SAMPLERATE_8000,
AudioFormat.ENCODING_PCM_16BIT);
}
/**
* start recording: set the parameters that correspond to a buffer that
* contains millisecondsPerAudioClip milliseconds of samples
*/
public boolean startRecordingForTime(int millisecondsPerAudioClip,
int sampleRate, int encoding)
{
float percentOfASecond = (float) millisecondsPerAudioClip / 1000.0f;
int numSamplesRequired = (int) ((float) sampleRate * percentOfASecond);
int bufferSize =
determineCalculatedBufferSize(sampleRate, encoding,
numSamplesRequired);
return doRecording(sampleRate, encoding, bufferSize,
numSamplesRequired, DEFAULT_BUFFER_INCREASE_FACTOR);
}
/**
* start recording: Use a minimum audio buffer and a read buffer of the same
* size.
*/
public boolean startRecording(final int sampleRate, int encoding)
{
int bufferSize = determineMinimumBufferSize(sampleRate, encoding);
return doRecording(sampleRate, encoding, bufferSize, bufferSize,
DEFAULT_BUFFER_INCREASE_FACTOR);
}
private int determineMinimumBufferSize(final int sampleRate, int encoding)
{
int minBufferSize =
AudioRecord.getMinBufferSize(sampleRate,
AudioFormat.CHANNEL_IN_MONO, encoding);
return minBufferSize;
}
/**
* Calculate audio buffer size such that it holds numSamplesInBuffer and is
* bigger than the minimum size<br>
*
* @param numSamplesInBuffer
* Make the audio buffer size big enough to hold this many
* samples
*/
private int determineCalculatedBufferSize(final int sampleRate,
int encoding, int numSamplesInBuffer)
{
int minBufferSize = determineMinimumBufferSize(sampleRate, encoding);
int bufferSize;
// each sample takes two bytes, need a bigger buffer
if (encoding == AudioFormat.ENCODING_PCM_16BIT)
{
bufferSize = numSamplesInBuffer * 2;
}
else
{
bufferSize = numSamplesInBuffer;
}
if (bufferSize < minBufferSize)
{
Log.w(TAG, "Increasing buffer to hold enough samples "
+ minBufferSize + " was: " + bufferSize);
bufferSize = minBufferSize;
}
return bufferSize;
}
/**
* Records audio until stopped the {@link #task} is canceled,
* {@link #continueRecording} is false, or {@link #clipListener} returns
* true <br>
* records audio to a short [readBufferSize] and passes it to
* {@link #clipListener} <br>
* uses an audio buffer of size bufferSize * bufferIncreaseFactor
*
* @param recordingBufferSize
* minimum audio buffer size
* @param readBufferSize
* reads a buffer of this size
* @param bufferIncreaseFactor
* to increase recording buffer size beyond the minimum needed
*/
private boolean doRecording(final int sampleRate, int encoding,
int recordingBufferSize, int readBufferSize,
int bufferIncreaseFactor)
{
if (recordingBufferSize == AudioRecord.ERROR_BAD_VALUE)
{
Log.e(TAG, "Bad encoding value, see logcat");
return false;
}
else if (recordingBufferSize == AudioRecord.ERROR)
{
Log.e(TAG, "Error creating buffer size");
return false;
}
// give it extra space to prevent overflow
int increasedRecordingBufferSize =
recordingBufferSize * bufferIncreaseFactor;
recorder =
new AudioRecord(AudioSource.MIC, sampleRate,
AudioFormat.CHANNEL_IN_MONO, encoding,
increasedRecordingBufferSize);
final short[] readBuffer = new short[readBufferSize];
continueRecording = true;
Log.d(TAG, "start recording, " + "recording bufferSize: "
+ increasedRecordingBufferSize
+ " read buffer size: " + readBufferSize);
//Note: possible IllegalStateException
//if audio recording is already recording or otherwise not available
//AudioRecord.getState() will be AudioRecord.STATE_UNINITIALIZED
recorder.startRecording();
while (continueRecording)
{
int bufferResult = recorder.read(readBuffer, 0, readBufferSize);
//in case external code stopped this while read was happening
if ((!continueRecording) || ((task != null) && task.isCancelled()))
{
break;
}
// check for error conditions
if (bufferResult == AudioRecord.ERROR_INVALID_OPERATION)
{
Log.e(TAG, "error reading: ERROR_INVALID_OPERATION");
}
else if (bufferResult == AudioRecord.ERROR_BAD_VALUE)
{
Log.e(TAG, "error reading: ERROR_BAD_VALUE");
}
else
// no errors, do processing
{
heard = clipListener.heard(readBuffer, sampleRate);
if (heard)
{
stopRecording();
}
}
}
done();
return heard;
}
public boolean isRecording()
{
return continueRecording;
}
public void stopRecording()
{
continueRecording = false;
}
/**
* need to call this when completely done with recording
*/
public void done()
{
Log.d(TAG, "shut down recorder");
if (recorder != null)
{
recorder.stop();
recorder.release();
recorder = null;
}
}
/**
* @param audioData
* will be filled when reading the audio data
*/
private void setOnPositionUpdate(final short[] audioData,
final int sampleRate, int numSamplesInBuffer)
{
// possibly do it that way
// setOnNotification(audioData, sampleRate, numSamplesInBuffer);
OnRecordPositionUpdateListener positionUpdater =
new OnRecordPositionUpdateListener()
{
@Override
public void onPeriodicNotification(AudioRecord recorder)
{
// no need to read the audioData again since it was just
// read
heard = clipListener.heard(audioData, sampleRate);
if (heard)
{
Log.d(TAG, "heard audio");
stopRecording();
}
}
@Override
public void onMarkerReached(AudioRecord recorder)
{
Log.d(TAG, "marker reached");
}
};
// get notified after so many samples collected
recorder.setPositionNotificationPeriod(numSamplesInBuffer);
recorder.setRecordPositionUpdateListener(positionUpdater);
}
} | Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.record;
/**
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*
*/
public interface AudioClipListener
{
public boolean heard(short [] audioData, int sampleRate);
}
| Java |
package root.gast.audio.util;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.util.Log;
/**
* log any callbacks
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class RecorderErrorLoggerListener implements OnErrorListener, OnInfoListener
{
private static final String D_LOG = RecorderErrorLoggerListener.class.getName();
public void onError(MediaRecorder mr, int what, int extra)
{
Log.d(D_LOG, "error in media recorder detected: " + what + " ex: " + extra);
if (what == MediaRecorder.MEDIA_RECORDER_ERROR_UNKNOWN)
{
Log.d(D_LOG, "it was a media recorder error unknown");
}
else
{
Log.d(D_LOG, "unknown media error");
}
}
public void onInfo(MediaRecorder mr, int what, int extra)
{
Log.d(D_LOG, "info in media recorder detected: " + what + " ex: " + extra);
if (what == MediaRecorder.MEDIA_RECORDER_INFO_UNKNOWN)
{
Log.d(D_LOG, "it was a MEDIA_INFO_UNKNOWN");
}
else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED)
{
Log.d(D_LOG, "it was a MEDIA_RECORDER_INFO_MAX_DURATION_REACHED");
}
else if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED)
{
Log.d(D_LOG, "it was a MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED");
}
else
{
Log.d(D_LOG, "unknown info");
}
}
}
| Java |
/*
* Copyright 2012 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.audio.util;
import java.io.IOException;
import java.io.PrintWriter;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;
/**
* various utility methods for audio processing
* @author Greg Milette <<a href="mailto:gregorym@gmail.com">gregorym@gmail.com</a>>
*/
public class AudioUtil
{
private static final String TAG = "AudioUtil";
/**
* creates a media recorder, or throws a {@link IOException} if
* the path is not valid.
* @param sdCardPath should contain a .3gp extension
*/
public static MediaRecorder prepareRecorder(String sdCardPath)
throws IOException
{
if (!isStorageReady())
{
throw new IOException("SD card is not available");
}
MediaRecorder recorder = new MediaRecorder();
//set a custom listener that just logs any messages
RecorderErrorLoggerListener recorderListener =
new RecorderErrorLoggerListener();
recorder.setOnErrorListener(recorderListener);
recorder.setOnInfoListener(recorderListener);
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Log.d(TAG, "recording to: " + sdCardPath);
recorder.setOutputFile(sdCardPath);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.prepare();
return recorder;
}
private static boolean isStorageReady()
{
String cardstatus = Environment.getExternalStorageState();
if (cardstatus.equals(Environment.MEDIA_REMOVED)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTED)
|| cardstatus.equals(Environment.MEDIA_UNMOUNTABLE)
|| cardstatus.equals(Environment.MEDIA_MOUNTED_READ_ONLY))
{
return false;
}
else
{
if (cardstatus.equals(Environment.MEDIA_MOUNTED))
{
return true;
}
else
{
return false;
}
}
}
public static boolean hasMicrophone(Context context)
{
return context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_MICROPHONE);
}
public static boolean isSilence(short [] data)
{
boolean silence = false;
int RMS_SILENCE_THRESHOLD = 2000;
if (rootMeanSquared(data) < RMS_SILENCE_THRESHOLD)
{
silence = true;
}
return silence;
}
public static double rootMeanSquared(short[] nums)
{
double ms = 0;
for (int i = 0; i < nums.length; i++)
{
ms += nums[i] * nums[i];
}
ms /= nums.length;
return Math.sqrt(ms);
}
public static int countZeros(short [] audioData)
{
int numZeros = 0;
for (int i = 0; i < audioData.length; i++)
{
if (audioData[i] == 0)
{
numZeros++;
}
}
return numZeros;
}
public static double secondsPerSample(int sampleRate)
{
return 1.0/(double)sampleRate;
}
public static int numSamplesInTime(int sampleRate, float seconds)
{
return (int)((float)sampleRate * (float)seconds);
}
public static void outputData(short [] data, PrintWriter writer)
{
for (int i = 0; i < data.length; i++)
{
writer.println(String.valueOf(data[i]));
}
if (writer.checkError())
{
Log.w(TAG, "Error writing sensor event data");
}
}
}
| Java |
/*
* Copyright 2011 Greg Milette and Adam Stroud
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package root.gast.playground.speech.activation;
import fabworkz.anna.SpeechRecognitionLauncher;
import root.gast.speech.activation.SpeechActivationService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ShowResultsSpeechActivationBroadcastReceiver extends
BroadcastReceiver
{
private static final String TAG =
"ShowResultsSpeechActivationBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(
SpeechActivationService.ACTIVATION_RESULT_BROADCAST_NAME))
{
if (intent
.getBooleanExtra(
SpeechActivationService.ACTIVATION_RESULT_INTENT_KEY,
false))
{
Log.d(TAG,
"ShowResultsSpeechActivationBroadcastReceiver taking action");
// launch something that prompts the user...
Intent i = new Intent(context, SpeechRecognitionLauncher.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package fabworkz.anna;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* AniVisApp.java
*/
package anivis;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.util.Properties;
import anivis.ui.AniVisFrame;
import anivis.ui.Controller;
import anivis.db.QueryLayer;
import anivis.ui.map.MapView;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
import com.bbn.openmap.MultipleSoloMapComponentException;
/**
* The main class of the application.
*/
public class AniVisApp extends Application {
private Controller controller;
private Properties properties;
public static AniVisApp application;
public AniVisApp() {
}
/**
* Main method launching the application.
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException, MultipleSoloMapComponentException {
// properties of the application
Properties props = new Properties();
loadResource("AniVis.properties", props);
// create the app
application = new AniVisApp();
// create the controller
Controller controller = new Controller();
// prepare the stuff before creating the frame
application.controller = controller;
application.properties = props;
// ui frame
AniVisFrame anivisFrame = new AniVisFrame(props, controller);
// and display the frame
anivisFrame.pack();
anivisFrame.setVisible(true);
}
public String getString(String property) {
return properties.getProperty(property);
}
public static AniVisApp getApplication() {
return application;
}
public Controller getController() {
return controller;
}
/**
* This method, called from main(), bundles functionality that
* once was being called twice, because there were two resource
* files being loaded, not just one, as is currently the case.
* Rather than put this code back into main(), it's been kept as a
* separate method in case we use more than one resource file
* again.
*/
private static void loadResource(String resources, Properties props) {
try {
InputStream in = new FileInputStream(resources);
if (props == null) {
System.err.println("Unable to locate resources: " + resources);
System.err.println("Using default resources.");
} else {
try {
props.load(in);
} catch (java.io.IOException e) {
System.err.println("Caught IOException loading resources: "
+ resources);
System.err.println("Using default resources.");
}
}
}
catch (Exception e) {
System.err.println(e);
}
}
@Override
protected void startup() {
// TODO Auto-generated method stub
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.db;
import anivis.base.DataAvailableNotification;
import java.sql.ResultSet;
import java.util.Set;
/**
*
* @author siberion
*/
public class QueryLayer extends java.util.Observable
{
public enum RestrictionType
{
None,
TimeWindow,
TimeSpan,
TemporalAggregation,
Latitude,
Longitude,
SpatialAggregation,
NominalFilter
}
public enum DatasetAttribute
{
Country,
StateProvince,
Locality,
Species
}
public enum SpeciesAttribute
{
CommonName,
ScientificName,
Kingdom,
Phylum,
Class,
Order,
Family,
Genus,
Epithet
}
public static abstract class Restriction
{
RestrictionType t;
public Restriction() {
this.t = RestrictionType.None;
}
public Restriction(RestrictionType t) {
this.t = t;
}
public RestrictionType getType() {
return t;
}
}
public static class RangeRestriction extends Restriction
{
double lo, hi;
public RangeRestriction(double lo, double hi, RestrictionType t) {
super(t);
this.lo = lo;
this.hi = hi;
}
}
public static class SetRestriction extends Restriction
{
DatasetAttribute attr;
Set<String> values;
public SetRestriction(DatasetAttribute attr, Set<String> values) {
super(RestrictionType.NominalFilter);
this.attr = attr;
this.values = values;
}
}
public static class Aggregation extends Restriction
{
double gridsize;
public Aggregation(double gridsize, RestrictionType t) {
super(t);
this.gridsize = gridsize;
}
}
static class QueryInfo
{
QueryLayer _parent;
String _query;
double gridsize;
boolean aggregate;
DataAvailableNotification _notification;
}
static class AsynchronousQuery implements java.lang.Runnable
{
QueryInfo _info;
public AsynchronousQuery(QueryInfo info)
{
_info = info;
}
public void run()
{
prefuse.data.Table _lastQueryWin, _lastQuerySpan;
int c_lat, c_long, c_agg, c_date, c_spci, row_num;
try
{
java.sql.Statement stmt = _info._parent._con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
java.sql.ResultSet res = stmt.executeQuery(_info._query);
_lastQueryWin = new prefuse.data.Table();
_lastQueryWin.addColumn("latitude", double.class);
_lastQueryWin.addColumn("longitude", double.class);
_lastQueryWin.addColumn("aggregation", int.class, 0);
_lastQueryWin.addColumn("date", long.class);
_lastQueryWin.addColumn("species", int.class);
_lastQuerySpan = new prefuse.data.Table();
_lastQuerySpan.addColumn("latitude", double.class);
_lastQuerySpan.addColumn("longitude", double.class);
_lastQuerySpan.addColumn("aggregation", int.class, 0);
_lastQuerySpan.addColumn("date", long.class);
_lastQuerySpan.addColumn("species", int.class);
c_lat = _lastQueryWin.getColumnNumber("latitude");
c_long = _lastQueryWin.getColumnNumber("longitude");
c_agg = _lastQueryWin.getColumnNumber("aggregation");
c_date = _lastQueryWin.getColumnNumber("date");
c_spci = _lastQueryWin.getColumnNumber("species");
while (res.next())
{
if (res.getBoolean(5))
{
row_num = _lastQueryWin.addRow();
_lastQueryWin.set(row_num, c_lat, res.getObject(1));
_lastQueryWin.set(row_num, c_long, res.getObject(2));
_lastQueryWin.set(row_num, c_date, res.getObject(3));
_lastQueryWin.set(row_num, c_spci, res.getObject(4));
}
row_num = _lastQuerySpan.addRow();
_lastQuerySpan.set(row_num, c_lat, res.getObject(1));
_lastQuerySpan.set(row_num, c_long, res.getObject(2));
_lastQuerySpan.set(row_num, c_date, res.getObject(3));
_lastQuerySpan.set(row_num, c_spci, res.getObject(4));
}
res.close();
_info._parent._lastQuerySpan = _lastQuerySpan;
_info._parent._lastQueryWin = _lastQueryWin;
if (_info.aggregate) _info._parent._aggregatedData = _info._parent.spatialAggregation(_info.gridsize, _lastQueryWin);
}
catch(java.sql.SQLException se)
{
return;
}
_info._parent.setChanged();
_info._parent.notifyObservers(_info._notification);
}
}
public QueryLayer() throws java.sql.SQLException, ClassNotFoundException
{
String url = "jdbc:mysql://localhost:3306/anivis";
java.sql.ResultSet res = null;
Class.forName("com.mysql.jdbc.Driver");
_con = java.sql.DriverManager.getConnection(url, "anivis", "anivisdb239847");
_stmt = _con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
res = _stmt.executeQuery("SELECT COUNT(*) FROM dataset_pri;");
res.next();
_total = res.getInt(1);
_fields = new java.util.HashMap<DatasetAttribute, String>();
_fields.put(DatasetAttribute.Country, "Country");
_fields.put(DatasetAttribute.StateProvince, "StateProvince");
_fields.put(DatasetAttribute.Locality, "Locality");
_fields.put(DatasetAttribute.Species, "species_id");
_auxfields = new java.util.HashMap<SpeciesAttribute, String>();
_auxfields.put(SpeciesAttribute.CommonName, "Common_Name");
_auxfields.put(SpeciesAttribute.ScientificName, "Scientific_Name");
_auxfields.put(SpeciesAttribute.Kingdom, "Kingdom");
_auxfields.put(SpeciesAttribute.Phylum, "Phylum");
_auxfields.put(SpeciesAttribute.Class, "Class");
_auxfields.put(SpeciesAttribute.Order, "Order");
_auxfields.put(SpeciesAttribute.Family, "Family");
_auxfields.put(SpeciesAttribute.Genus, "Genus");
_auxfields.put(SpeciesAttribute.Epithet, "Epithet");
_reQuery = true;
_reAggregate = true;
_timeSpan = null;
_timeWin = null;
_latRange = null;
_longRange = null;
_filters = new java.util.HashMap<DatasetAttribute, SetRestriction>();
}
/**
* Impose a restriction on further queries; will overwrite existing restrictions of the same type
* @param r The restriction object
* @return Always true - no failure condition
*/
public boolean setRestriction(Restriction r)
{
switch (r.t)
{
case TimeSpan:
_timeSpanNew = RangeRestriction.class.cast(r);
break;
case TimeWindow:
_timeWinNew = RangeRestriction.class.cast(r);
break;
case Latitude:
_latRangeNew = RangeRestriction.class.cast(r);
break;
case Longitude:
_longRangeNew = RangeRestriction.class.cast(r);
break;
case TemporalAggregation:
_tempAgg = Aggregation.class.cast(r);
_reAggregate = true;
break;
case SpatialAggregation:
_spatAgg = Aggregation.class.cast(r);
_reAggregate = true;
break;
case NominalFilter:
_filters.put(SetRestriction.class.cast(r).attr, SetRestriction.class.cast(r));
_reQuery = true;
_reAggregate = true;
break;
}
return true;
}
/**
* Remove the restriction identified by t, if one has been specified. Warning:
* Specifying RestrictionType::NominalFilter clears all filters of that type.
* @param t
* @return true
*/
public boolean clearRestriction(RestrictionType t)
{
switch (t)
{
case TimeSpan:
_timeSpanNew = null;
break;
case TimeWindow:
_timeWinNew = null;
break;
case Latitude:
_latRangeNew = null;
break;
case Longitude:
_longRangeNew = null;
break;
case TemporalAggregation:
if (_tempAgg != null)
{
_tempAgg = null;
_reAggregate = true;
}
return true;
case SpatialAggregation:
if (_spatAgg != null)
{
_spatAgg = null;
_reAggregate = true;
}
return true;
case NominalFilter:
_filters.clear();
_reQuery = true;
_reAggregate = true;
break;
}
return true;
}
/**
* Remove restrictions of type NominalFilter individually.
* @param a Attribute to remove the filter for
* @return true
*/
public boolean clearFilter(DatasetAttribute a)
{
_filters.remove(a);
_reQuery = true;
_reAggregate = true;
return true;
}
/**
* Prepares data as indicated by filters specified through set/clearRestriction
* @param notification Arbitrary object to use for notification
* @return Always true
*/
public boolean prepareData() throws java.sql.SQLException
{
java.util.Set<RestrictionType> r = new java.util.HashSet<RestrictionType>();
QueryInfo info = new QueryInfo();
AsynchronousQuery aq;
if (qthread != null)
{
qthread.interrupt();
try { qthread.join(); } catch (InterruptedException ex) {}
}
info._parent = this;
info.aggregate = (_spatAgg != null);
if (info.aggregate) info.gridsize = _spatAgg.gridsize;
info._query = updateQuery();
if (_timeSpan != null) r.add(RestrictionType.TimeSpan);
if (_timeWin != null) r.add(RestrictionType.TimeWindow);
if (_latRange != null) r.add(RestrictionType.Latitude);
if (_longRange != null) r.add(RestrictionType.Longitude);
if (_filters.size() > 0) r.add(RestrictionType.NominalFilter);
if (_spatAgg != null) r.add(RestrictionType.SpatialAggregation);
if (_tempAgg != null) r.add(RestrictionType.TemporalAggregation);
info._notification = new DataAvailableNotification(r);
aq = new AsynchronousQuery(info);
qthread = new Thread(aq);
qthread.run();
return true;
}
/**
* Retrieve number of records in a filter
* @param r Filters to apply to data
* @return Number of records
* @throws java.sql.SQLException
*/
public int getDataCount(java.util.Set<RestrictionType> r) throws java.sql.SQLException
{
boolean sagg, tagg, window;
prefuse.data.Table t;
sagg = r.contains(RestrictionType.SpatialAggregation);
tagg = r.contains(RestrictionType.TemporalAggregation);
window = r.contains(RestrictionType.TimeWindow);
if (sagg && _spatAgg != null) t = _aggregatedData;
//else if (tagg && _tempAgg != null) t = temporalAggregation(_spatAgg.gridsize, (window ? _lastQueryWin : _lastQuerySpan));
else t = (window ? _lastQueryWin : _lastQuerySpan);
return t.getRowCount();
}
/**
* Retrieve filtered set of records from dataset
* @param r Filters to apply to data
* @param t Table to receive result (prior contents lost!)
* @return Number of records returned
* @throws java.sql.SQLException
*/
public prefuse.data.Table getData(java.util.Set<RestrictionType> r) throws java.sql.SQLException
{
boolean sagg, tagg, window;
sagg = r.contains(RestrictionType.SpatialAggregation);
tagg = r.contains(RestrictionType.TemporalAggregation);
window = r.contains(RestrictionType.TimeWindow);
if (sagg && _spatAgg != null) return _aggregatedData;
//else if (tagg && _tempAgg != null) t = temporalAggregation(_spatAgg.gridsize, (window ? _lastQueryWin : _lastQuerySpan));
else return (window ? _lastQueryWin : _lastQuerySpan);
}
/**
* Retrieve set of possible values for a nominal attribute
* @param a Attribute to look at
* @return Set of possible values
* @throws java.sql.SQLException
*/
public java.util.Set<String> getDistinctValues(DatasetAttribute a) throws java.sql.SQLException
{
java.util.Set<String> values = new java.util.HashSet<String>();
java.sql.ResultSet res = null;
String s, query;
query = "SELECT DISTINCT `" + _fields.get(a) + "` FROM dataset_pri ORDER BY `" + _fields.get(a) + "` ASC";
System.out.println(query);
res = _stmt.executeQuery(query);
while (res.next())
{
s = res.getString(1);
if (!res.wasNull()) values.add(s);
}
res.close();
return values;
}
public java.util.Set<String> getDistinctValues(SpeciesAttribute a) throws java.sql.SQLException
{
java.util.Set<String> values = new java.util.HashSet<String>();
java.sql.ResultSet res = null;
String s, query;
query = "SELECT DISTINCT `" + _auxfields.get(a) + "` FROM dataset_sec ORDER BY `" + _auxfields.get(a) + "` ASC";
System.out.println(query);
res = _stmt.executeQuery(query);
while (res.next())
{
s = res.getString(1);
if (!res.wasNull()) values.add(s);
}
res.close();
return values;
}
private java.sql.Connection _con;
private java.sql.Statement _stmt;
private int _total;
private java.util.HashMap<DatasetAttribute, String> _fields;
private java.util.HashMap<SpeciesAttribute, String> _auxfields;
private prefuse.data.Table _lastQueryWin, _lastQuerySpan, _aggregatedData;
private boolean _reQuery, _reAggregate;
private RangeRestriction _timeSpan, _timeSpanNew, _timeWin, _timeWinNew,
_latRange, _latRangeNew, _longRange, _longRangeNew;
private Aggregation _tempAgg, _spatAgg;
private java.util.HashMap<DatasetAttribute, SetRestriction> _filters;
private java.lang.Thread qthread;
/**
* Private function to formulate a query based on a filter
* @param fields String identifying fields to return from SQL SELECT
* @param r Filter to apply
* @return The query
*/
private String BuildQuery(String fields, java.util.Set<RestrictionType> r)
{
String query = "SELECT " + fields + " FROM dataset_pri WHERE 1";
java.util.Iterator<String> j;
java.util.Iterator<DatasetAttribute> k;
Restriction rstr;
RangeRestriction rr;
SetRestriction sr;
Aggregation ar;
boolean firstel;
String str = null;
double gridsize = 0.0;
if (_timeSpan != null && r.contains(RestrictionType.TimeSpan)) query += " AND `Date_Collected` >= " + _timeSpan.lo + " AND `Date_Collected` <= " + _timeSpan.hi;
if (_latRange != null && r.contains(RestrictionType.Latitude)) query += " AND `Decimal_Latitude` >= " + _latRange.lo + " AND `Decimal_Latitude` <= " + _latRange.hi;
if (_longRange != null && r.contains(RestrictionType.Longitude)) query += " AND `Decimal_Longitude` >= " + _longRange.lo + " AND `Decimal_Longitude` <= " + _longRange.hi;
k = _filters.keySet().iterator();
while (k.hasNext() && r.contains(RestrictionType.NominalFilter))
{
sr = _filters.get(k.next());
j = sr.values.iterator();
firstel = true;
while (j.hasNext())
{
if (firstel)
{
query += " AND `" + _fields.get(sr.attr) + "` IN (";
firstel = false;
}
else query += ",";
str = j.next();
str.replace("'", "!^");
if (sr.attr == DatasetAttribute.Species) query += str;
else query += "'" + str + "'";
}
query += ")";
}
if (_spatAgg != null) query += " ORDER BY (FLOOR(Decimal_Longitude / "
+ _spatAgg.gridsize + ") * 500) + Decimal_Latitude ASC";
return query + ";";
}
private String updateQuery()
{
String query = null;
java.sql.ResultSet res = null;
double winlo, winhi;
java.util.HashSet<RestrictionType> restriction = new java.util.HashSet<RestrictionType>();
if (_timeSpan != _timeSpanNew ) _reQuery = true;
if (_timeWin != _timeWinNew ) _reQuery = true;
if (_latRange != _latRangeNew ) _reQuery = true;
if (_longRange != _longRangeNew) _reQuery = true;
if (!_reQuery) return null;
if (_timeSpan != _timeSpanNew ) _timeSpan = _timeSpanNew;
if (_timeWin != _timeWinNew ) _timeWin = _timeWinNew;
if (_latRange != _latRangeNew ) _latRange = _latRangeNew;
if (_longRange != _longRangeNew) _longRange = _longRangeNew;
if (_timeWin == null)
{
if (_timeSpan == null)
{
winlo = 0;
winhi = 1202770800;
}
else
{
winlo = _timeSpan.lo;
winhi = _timeSpan.hi;
}
}
else
{
winlo = _timeWin.lo;
winhi = _timeWin.hi;
}
restriction.add(RestrictionType.TimeSpan);
restriction.add(RestrictionType.Latitude);
restriction.add(RestrictionType.Longitude);
restriction.add(RestrictionType.NominalFilter);
query = BuildQuery("Decimal_Latitude,Decimal_Longitude,Date_Collected,Species_Id,"
+ "(Date_Collected >= " + winlo + " AND Date_Collected <= " + winhi + ") AS InWindow", restriction);
System.out.println(query);
_reQuery = false;
return query;
}
private prefuse.data.Table temporalAggregation(double grid, prefuse.data.Table in)
{
return in;
}
/**
* Combine data points that are located in the same cell of some grid. Be aware that for this
* function to work correctly, the data points MUST be ordered such that all the data points
* within one cell appear in a consecutive sequence in the input table.
* @param grid
* @param in
* @return
*/
private prefuse.data.Table spatialAggregation(double grid, prefuse.data.Table in)
{
int count = 0, gx = -1000, gy = -1000, r, newrow, tuplecount;
double dlat = 0.0, dlong = 0.0, dlatavg = 0.0, dlongavg = 0.0;
if (grid <= 1.0) return in;
prefuse.data.Table out = new prefuse.data.Table();
out.addColumns(in.getSchema());
out.removeColumn("date");
for (r = 1; in.isValidRow(r); ++r)
{
dlat = in.getDouble(r, "latitude");
dlong = in.getDouble(r, "longitude");
if (gx != java.lang.Math.floor(dlat / grid) || gy != java.lang.Math.floor(dlong / grid))
{
if (count > 0)
{
newrow = out.addRow();
out.setDouble(newrow, "latitude", dlatavg / count);
out.setDouble(newrow, "longitude", dlongavg / count);
out.setInt(newrow, "aggregation", count);
//out.setInt(newrow, "species", in.getInt(r, "species"));
}
dlatavg = 0.0;
dlongavg = 0.0;
count = 0;
gx = (int)java.lang.Math.floor(dlat / grid);
gy = (int)java.lang.Math.floor(dlong / grid);
}
dlatavg += dlat;
dlongavg += dlong;
++count;
}
if (count > 0)
{
newrow = out.addRow();
out.setDouble(newrow, "latitude", dlatavg / count);
out.setDouble(newrow, "longitude", dlongavg / count);
out.setInt(newrow, "aggregation", count);
//out.setInt(newrow, "species", in.getInt(r, "species"));
}
return out;
}
}
| Java |
/*
* AniVisView.java
*/
package anivis;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* The application's main frame.
*/
public class AniVisView extends FrameView {
public AniVisView(SingleFrameApplication app) {
super(app);
}
// public AniVisView(SingleFrameApplication app) {
// super(app);
//
// initComponents();
//
// // status bar initialization - message timeout, idle icon and busy animation, etc
// ResourceMap resourceMap = getResourceMap();
// int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
// messageTimer = new Timer(messageTimeout, new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// statusMessageLabel.setText("");
// }
// });
// messageTimer.setRepeats(false);
// int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
// for (int i = 0; i < busyIcons.length; i++) {
// busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
// }
// busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
// statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
// }
// });
// idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
// statusAnimationLabel.setIcon(idleIcon);
// progressBar.setVisible(false);
//
// // connecting action tasks to status bar via TaskMonitor
// TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
// taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
// public void propertyChange(java.beans.PropertyChangeEvent evt) {
// String propertyName = evt.getPropertyName();
// if ("started".equals(propertyName)) {
// if (!busyIconTimer.isRunning()) {
// statusAnimationLabel.setIcon(busyIcons[0]);
// busyIconIndex = 0;
// busyIconTimer.start();
// }
// progressBar.setVisible(true);
// progressBar.setIndeterminate(true);
// } else if ("done".equals(propertyName)) {
// busyIconTimer.stop();
// statusAnimationLabel.setIcon(idleIcon);
// progressBar.setVisible(false);
// progressBar.setValue(0);
// } else if ("message".equals(propertyName)) {
// String text = (String)(evt.getNewValue());
// statusMessageLabel.setText((text == null) ? "" : text);
// messageTimer.restart();
// } else if ("progress".equals(propertyName)) {
// int value = (Integer)(evt.getNewValue());
// progressBar.setVisible(true);
// progressBar.setIndeterminate(false);
// progressBar.setValue(value);
// }
// }
// });
// }
//
// @Action
// public void showAboutBox() {
// if (aboutBox == null) {
// JFrame mainFrame = AniVisApp.getApplication().getMainFrame();
// aboutBox = new AniVisAboutBox(mainFrame);
// aboutBox.setLocationRelativeTo(mainFrame);
// }
// AniVisApp.getApplication().show(aboutBox);
// }
//
// /** This method is called from within the constructor to
// * initialize the form.
// * WARNING: Do NOT modify this code. The content of this method is
// * always regenerated by the Form Editor.
// */
// @SuppressWarnings("unchecked")
// // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
// private void initComponents() {
//
// mainPanel = new javax.swing.JPanel();
// menuBar = new javax.swing.JMenuBar();
// javax.swing.JMenu fileMenu = new javax.swing.JMenu();
// javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
// javax.swing.JMenu helpMenu = new javax.swing.JMenu();
// javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
// statusPanel = new javax.swing.JPanel();
// javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
// statusMessageLabel = new javax.swing.JLabel();
// statusAnimationLabel = new javax.swing.JLabel();
// progressBar = new javax.swing.JProgressBar();
//
// mainPanel.setName("mainPanel"); // NOI18N
//
// org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
// mainPanel.setLayout(mainPanelLayout);
// mainPanelLayout.setHorizontalGroup(
// mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
// .add(0, 400, Short.MAX_VALUE)
// );
// mainPanelLayout.setVerticalGroup(
// mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
// .add(0, 252, Short.MAX_VALUE)
// );
//
// menuBar.setName("menuBar"); // NOI18N
//
// org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(anivis.AniVisApp.class).getContext().getResourceMap(AniVisView.class);
// fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
// fileMenu.setName("fileMenu"); // NOI18N
//
// javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(anivis.AniVisApp.class).getContext().getActionMap(AniVisView.class, this);
// exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
// exitMenuItem.setName("exitMenuItem"); // NOI18N
// fileMenu.add(exitMenuItem);
//
// menuBar.add(fileMenu);
//
// helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
// helpMenu.setName("helpMenu"); // NOI18N
//
// aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
// aboutMenuItem.setName("aboutMenuItem"); // NOI18N
// helpMenu.add(aboutMenuItem);
//
// menuBar.add(helpMenu);
//
// statusPanel.setName("statusPanel"); // NOI18N
//
// statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
//
// statusMessageLabel.setName("statusMessageLabel"); // NOI18N
//
// statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
// statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
//
// progressBar.setName("progressBar"); // NOI18N
//
// org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
// statusPanel.setLayout(statusPanelLayout);
// statusPanelLayout.setHorizontalGroup(
// statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
// .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
// .add(statusPanelLayout.createSequentialGroup()
// .addContainerGap()
// .add(statusMessageLabel)
// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 226, Short.MAX_VALUE)
// .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
// .add(statusAnimationLabel)
// .addContainerGap())
// );
// statusPanelLayout.setVerticalGroup(
// statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
// .add(statusPanelLayout.createSequentialGroup()
// .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
// .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
// .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
// .add(statusMessageLabel)
// .add(statusAnimationLabel)
// .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
// .add(3, 3, 3))
// );
//
// setComponent(mainPanel);
// setMenuBar(menuBar);
// setStatusBar(statusPanel);
// }// </editor-fold>//GEN-END:initComponents
//
// // Variables declaration - do not modify//GEN-BEGIN:variables
// private javax.swing.JPanel mainPanel;
// private javax.swing.JMenuBar menuBar;
// private javax.swing.JProgressBar progressBar;
// private javax.swing.JLabel statusAnimationLabel;
// private javax.swing.JLabel statusMessageLabel;
// private javax.swing.JPanel statusPanel;
// // End of variables declaration//GEN-END:variables
//
// private final Timer messageTimer;
// private final Timer busyIconTimer;
// private final Icon idleIcon;
// private final Icon[] busyIcons = new Icon[15];
// private int busyIconIndex = 0;
//
// private JDialog aboutBox;
}
| Java |
package anivis.ui;
import java.awt.Container;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Observable;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import anivis.AniVisApp;
import anivis.ui.map.AnimalLayer;
import anivis.ui.timeline.TimelineView;
import com.bbn.openmap.gui.OMComponentPanel;
import com.bbn.openmap.gui.OMToolComponent;
public class AttributeWindow extends OMToolComponent {
private JFrame frame = null;
private AnimalLayer animalLayer = null;
private Controller controller;
/**
* Tool interface method. The retrieval tool's interface. This
* method creates a button that will bring up the BeanPanel.
*
* @return A container that will contain the 'face' of this panel
* on the OpenMap ToolPanel.
*/
public Container getFace() {
JButton button = null;
if (getUseAsTool()) {
button = new JButton(new ImageIcon("share/img/bird.png"));
button.setBorderPainted(false);
button.setToolTipText("Open Attribute Windoww");
button.setMargin(new Insets(0, 0, 0, 0));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Opening AttributeView");
display();
}
});
}
return button;
}
/**
* Get the ActionListener that triggers the LayersPanel. Useful to have to
* provide an alternative way to bring up the LayersPanel.
*
* @return ActionListener
*/
private synchronized void display() {
if (frame == null) {
frame = new JFrame("Attributes");
JPanel panel = new AttributeView(AniVisApp.getApplication().getController().getQueryLayer());
frame.add(panel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
frame.setVisible(false);
}
});
frame.pack();
}
frame.setVisible(true);
}
}
| Java |
package anivis.ui;
import java.awt.BorderLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import anivis.ui.map.MapView;
import com.bbn.openmap.LatLonPoint;
import com.bbn.openmap.Layer;
import com.bbn.openmap.LayerHandler;
import com.bbn.openmap.MapBean;
import com.bbn.openmap.MapHandler;
import com.bbn.openmap.MouseDelegator;
import com.bbn.openmap.MultipleSoloMapComponentException;
import com.bbn.openmap.OMComponent;
import com.bbn.openmap.event.CoordMouseMode;
import com.bbn.openmap.gui.OMComponentPanel;
import com.bbn.openmap.gui.OMToolSet;
import com.bbn.openmap.gui.ToolPanel;
public class AniVisFrame extends JFrame {
/** Properties */
public static final String PROPERTY_ROOT = "anivis";
public static final String PROPERTY_SEPARATOR = ".";
public static final String PROPERTY_LAYERS = "layers";
public static final String PROPERTY_PANEL_COMPONENTS = "panelcomponents";
public static final String PROPERTY_MOUSE_MODES = "mousemodes";
public static final String PROPERTY_COMPONENTS = "components";
public static final String PROPERTY_MENUS = "menus";
private final Controller controller;
public AniVisFrame(Properties props, Controller controller)
throws MultipleSoloMapComponentException, ClassNotFoundException, IOException {
// Initialize the parent class (JFrame)
super("AniVis 2008");
this.controller = controller;
// Use a Border layout manager
getContentPane().setLayout(new BorderLayout());
// add menus
System.out.println("Adding menus...");
JMenu[] menus = getMenus(props);
if (menus.length > 0) {
JMenuBar menuBar = new JMenuBar();
for (int i = 0; i < menus.length; i++) {
menuBar.add(menus[i]);
}
setJMenuBar(menuBar);
}
// Call quit when the window's close box is clicked.
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
quit();
}
});
// the map bean will be the mapview itself...
System.out.println("Creating MapHandler");
// Create the BeanContext, known as the MapHandler.
MapHandler mapHandler = new MapHandler();
System.out.println("Creating MapBean");
// Create a MapBean, and add it to the MapHandler.
MapBean map = (MapBean)new MapView();
// Set the map's center property...
map.setCenter(new LatLonPoint(43.0f, -95.0f));
// and scale
map.setScale(80000000f);
mapHandler.add(map);
// Add the map to the JFrame
getContentPane().add(map, BorderLayout.CENTER);
System.out.println("Adding MouseEvent support...");
// Add Mouse handling objects. The MouseDelegator manages the
// MouseModes, controlling which one receives events from the
// MapBean. The active MouseMode sends events to the layers
// that want to receive events from it. The MouseDelegator
// will find the MapBean in the MapHandler, and hook itself up
// to it.
mapHandler.add(new MouseDelegator());
System.out.println("Adding generic components...");
OMComponent[] components = getComponents(props);
for (int i = 0; i < components.length; i++) {
mapHandler.add(components[i]);
}
System.out.println("Creating ToolPanel...");
// Add the standard panning and zoom GUI to the JFrame.
// Create the tool...
mapHandler.add(new OMToolSet());
// Create the ToolPanel. It will find the OMToolSet in the
// MapHandler.
ToolPanel toolPanel = new ToolPanel();
mapHandler.add(toolPanel);
// Add the ToolPanel to the right place in this JFrame.
getContentPane().add(toolPanel, BorderLayout.NORTH);
System.out.println("Creating Layers...");
Layer[] layers = getLayers(props);
// Use the LayerHandler to manage all layers, whether they are
// on the map or not. You can add a layer to the map by
// setting layer.setVisible(true).
LayerHandler layerHandler = new LayerHandler();
for (int i = 0; i < layers.length; i++) {
layers[i].setVisible(true);
layerHandler.addLayer(layers[i]);
}
System.out.println("Adding panel components...");
OMComponentPanel[] panelComponents = getPanelComponents(props);
for (int i = 0; i < panelComponents.length; i++) {
panelComponents[i].setVisible(true);
mapHandler.add(panelComponents[i]);
}
System.out.println("Adding mouse modes...");
CoordMouseMode[] modes = getMouseModes(props);
for (int i = 0; i < modes.length; i++) {
mapHandler.add(modes[i]);
}
mapHandler.add(layerHandler);
System.out.println("Done creating...");
}
/**
* Exits the application.
*/
protected void quit() {
System.exit(0);
}
private String getProperty(String propertyName, Properties p, boolean useRoot) {
String fullName = (useRoot ? (PROPERTY_ROOT + PROPERTY_SEPARATOR) : "") + propertyName;
String value = p.getProperty(fullName);
if (value == null) {
System.out.println("Property " + fullName + " not found!");
value = "";
}
return value;
}
private StringTokenizer getProperties(String propertyName, Properties p, String separator, boolean useRoot) {
String value = getProperty(propertyName, p, useRoot);
return new StringTokenizer(value, separator);
}
/**
* Returns an instance of a bean given by the property name.
* Internally, the name of the property to be looked for resolves to "anivis." + propertyName + ".class"
*/
private Object instantiate(String propertyName, Properties p) throws ClassNotFoundException, IOException {
String classNameValue = getProperty(propertyName + PROPERTY_SEPARATOR + "class", p, false);
System.out.println("Instantiating " + classNameValue);
return java.beans.Beans.instantiate(null, classNameValue);
}
/**
* Gets the names of the Layers to be loaded from the properties
* passed in, initializes them, and returns them.
*
* @param p the properties, among them the property represented by
* the String layersProperty above, which will tell us
* which Layers need to be loaded
* @return an array of Layers ready to be added to the map bean
* @see #layersProperty
*/
private Layer[] getLayers(Properties p) throws ClassNotFoundException, IOException {
StringTokenizer tokens = getProperties(PROPERTY_LAYERS, p, " ", true);
Layer[] layers = new Layer[tokens.countTokens()];
// instantiate and set the properties
for (int i = 0; i < layers.length; i++) {
String layerName = tokens.nextToken();
layers[i] = (Layer)instantiate(layerName, p);
layers[i].setProperties(layerName, p);
}
return layers;
}
private OMComponentPanel[] getPanelComponents(Properties p) throws ClassNotFoundException, IOException {
StringTokenizer tokens = getProperties(PROPERTY_PANEL_COMPONENTS, p, " ", true);
OMComponentPanel[] components = new OMComponentPanel[tokens.countTokens()];
// instantiate and set the properties
for (int i = 0; i < components.length; i++) {
String layerName = tokens.nextToken();
components[i] = (OMComponentPanel)instantiate(layerName, p);
components[i].setProperties(layerName, p);
}
return components;
}
private CoordMouseMode[] getMouseModes(Properties p) throws ClassNotFoundException, IOException {
StringTokenizer tokens = getProperties(PROPERTY_MOUSE_MODES, p, " ", true);
CoordMouseMode[] modes = new CoordMouseMode[tokens.countTokens()];
// instantiate and set the properties
for (int i = 0; i < modes.length; i++) {
String layerName = tokens.nextToken();
modes[i] = (CoordMouseMode)instantiate(layerName, p);
modes[i].setProperties(layerName, p);
}
return modes;
}
private OMComponent[] getComponents(Properties p) throws ClassNotFoundException, IOException {
StringTokenizer tokens = getProperties(PROPERTY_COMPONENTS, p, " ", true);
OMComponent[] components = new OMComponent[tokens.countTokens()];
// instantiate and set the properties
for (int i = 0; i < components.length; i++) {
String layerName = tokens.nextToken();
components[i] = (OMComponent)instantiate(layerName, p);
components[i].setProperties(layerName, p);
}
return components;
}
private JMenu[] getMenus(Properties p) throws ClassNotFoundException, IOException {
StringTokenizer tokens = getProperties(PROPERTY_MENUS, p, " ", true);
JMenu[] components = new JMenu[tokens.countTokens()];
// instantiate and set the properties
for (int i = 0; i < components.length; i++) {
String layerName = tokens.nextToken();
components[i] = (JMenu)instantiate(layerName, p);
}
return components;
}
}
| Java |
package anivis.ui.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import anivis.AniVisAboutBox;
public class HelpMenu extends JMenu {
public HelpMenu() {
super("Help");
setName("Help");
setMnemonic('H');
// add the about part
JMenuItem aboutMenu = new JMenuItem("About");
aboutMenu.setName("About");
aboutMenu.setMnemonic('H');
aboutMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
AniVisAboutBox aboutBox = new AniVisAboutBox((JFrame)HelpMenu.this.getParent().getParent().getParent().getParent());
aboutBox.setVisible(true);
}
});
add(aboutMenu);
}
}
| Java |
/*
* AttributeView.java
*
* Created on July 15, 2008, 7:42 PM
*/
package anivis.ui;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import anivis.AniVisApp;
/**
*
* @author siberion
*/
public class AttributeView extends javax.swing.JPanel {
/** Creates new form AttributeView */
public AttributeView(anivis.db.QueryLayer ql)
{
java.util.Set<String> names = null;
initComponents();
try {
names = ql.getDistinctValues(anivis.db.QueryLayer.SpeciesAttribute.CommonName);
} catch (SQLException ex) {
Logger.getLogger(AttributeView.class.getName()).log(Level.SEVERE, "Oh My God!", ex);
}
jList1.setListData(new java.util.Vector<String>(names));
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jPanel1 = new javax.swing.JPanel();
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jEditorPane1 = new javax.swing.JEditorPane();
setName("Form"); // NOI18N
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
jSplitPane1.setName("split"); // NOI18N
jPanel1.setName("jPanel1"); // NOI18N
jScrollPane2.setName("jScrollPane2"); // NOI18N
jList1.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jList1.setName("jList1"); // NOI18N
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jScrollPane2.setViewportView(jList1);
jLabel1.setText(AniVisApp.getApplication().getString("jLabel1.text")); // NOI18N
jLabel1.setName("jLabel1"); // NOI18N
jButton1.setText(AniVisApp.getApplication().getString("jButton1.text")); // NOI18N
jButton1.setName("jButton1"); // NOI18N
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
.add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.add(jButton1))
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(jPanel1Layout.createSequentialGroup()
.add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 24, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jScrollPane2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jButton1))
);
jSplitPane1.setRightComponent(jPanel1);
jScrollPane1.setName("jScrollPane1"); // NOI18N
jEditorPane1.setName("jEditorPane1"); // NOI18N
jScrollPane1.setViewportView(jEditorPane1);
jSplitPane1.setLeftComponent(jScrollPane1);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 317, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 361, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
//www.javabeginner.com/jtabbedpane.htm
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
if (evt.getValueIsAdjusting()) return;
if (jList1.getSelectedValue() == null) return;
String url = "http://en.wikipedia.org/wiki/" + (String)jList1.getSelectedValue();
url = url.replace(" ", "_").replace("!^", "'");
try {
jEditorPane1.setPage(url);
}
catch (java.io.IOException ioe)
{
}
}//GEN-LAST:event_jList1ValueChanged
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
jList1.clearSelection();
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JEditorPane jEditorPane1;
private javax.swing.JLabel jLabel1;
private javax.swing.JList jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JSplitPane jSplitPane1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* LayerView.java
*
* Created on July 11, 2008, 8:06 PM
*/
package anivis.ui.timeline;
import anivis.base.DataAvailableNotification;
import anivis.base.Notification;
import anivis.base.RestrictionNotification;
import anivis.db.QueryLayer.Restriction;
import anivis.db.QueryLayer.RestrictionType;
import anivis.layers.ObservationLayer;
import anivis.ui.Controller;
import java.util.AbstractSet;
import java.util.HashSet;
import java.util.Observable;
import java.util.Set;
import prefuse.Display;
/**
*
* @author urp
*/
public class LayerView extends Display implements java.util.Observer
{
private anivis.ui.Controller controller = null;
private ObservationLayer layer;
private boolean waitsForData = true;
/** Creates new form LayerView */
public LayerView()
{
initComponents();
anivis.AniVisApp.getApplication().getController().addObserver(this);
layer = new ObservationLayer("Avian Networks",true,true);
layer.setRestrictionTypes(createRestrictionTypes());
}
static protected Set<RestrictionType> createRestrictionTypes()
{
Set<RestrictionType> r = new HashSet<RestrictionType>();
r.add(RestrictionType.TimeSpan);
return r;
}
//protected addVisualization()
//{
//}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setName("Form"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 598, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 85, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
public void update(Observable sender, Object message)
{
Notification notification = (Notification) message;
if(notification.isRestrictionNotification())
{
RestrictionNotification n = (RestrictionNotification) notification;
if( layer.getRestrictionTypes().contains( n.getRestriction().getType() ) )
{ waitsForData = true; }
}
else
if(notification.isDataAvaialableNotification())
{
DataAvailableNotification n = (DataAvailableNotification) notification;
Set<RestrictionType> rT = n.getRestrictionTypes();
if(waitsForData && rT.contains(layer.getRestrictionTypes()))
{ /*get data*/
anivis.ui.Controller c = (Controller) sender;
layer.getData(c);
waitsForData = false;
}
}
}
}
| Java |
/*
* IntervalSlider.java
*
* Created on July 9, 2008, 7:22 PM
*/
package anivis.ui.timeline;
import anivis.base.TimeInterval;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.util.Date;
import java.util.GregorianCalendar;
/**
*
* @author urp
*/
public class IntervalSlider extends javax.swing.JComponent {
private Date curTime;
private TimeInterval curTimeWindow;
private TimeInterval curTimeSpan;
/** Creates new form IntervalSlider */
public IntervalSlider() {
initComponents();
curTime = new GregorianCalendar(1900,1,1).getTime();
curTimeSpan = new TimeInterval(new GregorianCalendar(1900,1,1).getTime(),
new GregorianCalendar(2000,1,1).getTime() );
curTimeWindow = new TimeInterval(new GregorianCalendar(1940,1,1).getTime(),
new GregorianCalendar(1960,1,1).getTime() );
}
public Date getCurrentTime() {
return curTime;
}
public void setCurrentTime(Date date) {
curTime = date;
}
public TimeInterval getTimeWindow()
{
return curTimeWindow;
}
public void setTimeWindow(TimeInterval interval)
{
curTimeWindow=interval;
}
public TimeInterval getTimeSpan()
{
return curTimeSpan;
}
public void setTimeSpan(TimeInterval interval)
{
curTimeSpan=interval;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
if(getTimeSpan().contains(getTimeWindow().getBegin()))
{
float posCenter = getWidth()
* (getCurrentTime().getTime()-getTimeSpan().getBeginTime())
/ getTimeSpan().getLengthInMillis();
Polygon curTimeIndicator = new Polygon();
curTimeIndicator.addPoint(0,0);
curTimeIndicator.addPoint(10,10);
curTimeIndicator.addPoint(20, 0);
g2d.drawPolygon(curTimeIndicator);
}//else
if(getTimeSpan().contains(getTimeWindow().getBegin()))
{
float posLeft = getWidth()
* (getTimeWindow().getBeginTime()-getTimeSpan().getBeginTime())
/ getTimeSpan().getLengthInMillis();
Polygon leftBoundIndicator = new Polygon();
leftBoundIndicator.addPoint(10,0);
leftBoundIndicator.addPoint(10,10);
leftBoundIndicator.addPoint(20, 0);
g2d.drawPolygon(leftBoundIndicator);
// g2d.drawLine();
}//else
// g2d.drawLine();
if(getTimeSpan().contains(getTimeWindow().getEnd()))
{
float posRight = getWidth()
* (getTimeWindow().getEndTime()-getTimeSpan().getBeginTime())
/ getTimeSpan().getLengthInMillis();
Polygon rightBoundIndicator = new Polygon();
rightBoundIndicator.addPoint(0,0);
rightBoundIndicator.addPoint(10,10);
rightBoundIndicator.addPoint(10, 0);
g2d.drawPolygon(rightBoundIndicator);
// g2d.drawLine();
}//else
// g2d.drawLine
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setName("Form"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 627, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 306, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* TimelineView.java
*
* Created on July 8, 2008, 8:51 PM
*/
package anivis.ui.timeline;
import anivis.base.TimeInterval;
import anivis.layers.Layer;
/**
*
* @author urp
*/
public class TimelineView extends javax.swing.JPanel {
private IntervalSlider slider;
private anivis.ui.Controller controller;
private TimeLabelPanel timeLabels;
/** Creates new form TimelineView */
public TimelineView(anivis.ui.Controller anivisController) {
initComponents();
controller = anivisController;
}
public TimeInterval getTimeSpan() {
return timeLabels.getTimeSpan();
}
public void addLayer(Layer layer)
{
//LayerView lv = new LayerView(layer);
//controller.addObserver(lv);
}
public void setTimeSpan(TimeInterval interval) {
timeLabels.setTimeSpan(interval);
}
public TimeInterval getTimeWindow() {
return slider.getTimeWindow();
}
public void setTimeWindow(TimeInterval interval) {
slider.setTimeWindow(interval);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jSplitPane1 = new javax.swing.JSplitPane();
jLayeredPane1 = new javax.swing.JLayeredPane();
timeLabelPanel1 = new anivis.ui.timeline.TimeLabelPanel();
jPanel1 = new javax.swing.JPanel();
setName("Form"); // NOI18N
jSplitPane1.setDividerLocation(500);
jSplitPane1.setName("jSplitPane1"); // NOI18N
jLayeredPane1.setName("LayerPane"); // NOI18N
timeLabelPanel1.setName("timeLabelPanel1"); // NOI18N
timeLabelPanel1.setLayout(new java.awt.FlowLayout());
timeLabelPanel1.setBounds(0, 0, 420, 70);
jLayeredPane1.add(timeLabelPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER);
jSplitPane1.setLeftComponent(jLayeredPane1);
jPanel1.setName("jPanel1"); // NOI18N
org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 315, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 282, Short.MAX_VALUE)
);
jSplitPane1.setRightComponent(jPanel1);
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 826, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 286, Short.MAX_VALUE)
.addContainerGap())
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JPanel jPanel1;
private javax.swing.JSplitPane jSplitPane1;
private anivis.ui.timeline.TimeLabelPanel timeLabelPanel1;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.ui.timeline;
import anivis.layers.ObservationLayer;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import prefuse.Constants;
import prefuse.Display;
import prefuse.Visualization;
import prefuse.action.ActionList;
import prefuse.action.RepaintAction;
import prefuse.action.assignment.ColorAction;
import prefuse.action.assignment.DataShapeAction;
import prefuse.action.layout.AxisLayout;
import prefuse.controls.ToolTipControl;
import prefuse.data.Table;
import prefuse.render.DefaultRendererFactory;
import prefuse.render.ShapeRenderer;
import prefuse.util.ColorLib;
import prefuse.visual.VisualItem;
import prefuse.visual.expression.VisiblePredicate;
/**
*
* @author urp
*/
public class ObservationScatterPlot extends Display
{
private static final String group = "data";
private ShapeRenderer m_shapeR = new ShapeRenderer(2);
public ObservationScatterPlot(ObservationLayer layer, String xfield, String yfield)
{
this(layer, xfield, yfield, null);
}
public ObservationScatterPlot(ObservationLayer layer, String xfield, String yfield, String sfield)
{
super(new Visualization());
// --------------------------------------------------------------------
// STEP 1: setup the visualized data
m_vis.addTable(group, layer.getTable());
DefaultRendererFactory rf = new DefaultRendererFactory(m_shapeR);
m_vis.setRendererFactory(rf);
// --------------------------------------------------------------------
// STEP 2: create actions to process the visual data
// set up the actions
AxisLayout x_axis = new AxisLayout(group, xfield,
Constants.X_AXIS, VisiblePredicate.TRUE);
m_vis.putAction("x", x_axis);
AxisLayout y_axis = new AxisLayout(group, yfield,
Constants.Y_AXIS, VisiblePredicate.TRUE);
m_vis.putAction("y", y_axis);
ColorAction color = new ColorAction(group,
VisualItem.STROKECOLOR, ColorLib.rgb(100,100,255));
m_vis.putAction("color", color);
DataShapeAction shape = new DataShapeAction(group, sfield);
m_vis.putAction("shape", shape);
ActionList draw = new ActionList();
draw.add(x_axis);
draw.add(y_axis);
if ( sfield != null )
draw.add(shape);
draw.add(color);
draw.add(new RepaintAction());
m_vis.putAction("draw", draw);
// --------------------------------------------------------------------
// STEP 3: set up a display and ui components to show the visualization
setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
setSize(700,450);
setHighQuality(true);
ToolTipControl ttc = new ToolTipControl(new String[] {xfield,yfield});
addControlListener(ttc);
// --------------------------------------------------------------------
// STEP 4: launching the visualization
m_vis.run("draw");
}
public void setLayer(ObservationLayer newLayer)
{
m_vis.removeGroup(group);
m_vis.addTable(group, newLayer.getTable());
}
public int getPointSize() {
return m_shapeR.getBaseSize();
}
public void setPointSize(int size) {
m_shapeR.setBaseSize(size);
repaint();
}
}
| Java |
package anivis.ui.timeline;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Insets;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Observable;
import java.util.Properties;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.bbn.openmap.I18n;
import com.bbn.openmap.LatLonPoint;
import com.bbn.openmap.LayerHandler;
import com.bbn.openmap.MapBean;
import com.bbn.openmap.MapHandler;
import com.bbn.openmap.PropertyHandler;
import com.bbn.openmap.gui.LayersPanel;
import com.bbn.openmap.gui.OMToolComponent;
import com.bbn.openmap.gui.OMToolSet;
import com.bbn.openmap.gui.WindowSupport;
import com.bbn.openmap.util.Debug;
import anivis.ui.Controller;
import anivis.ui.map.AnimalLayer;
import anivis.ui.timeline.TimelineView;
import java.util.Observer;
public class TimeLineWindow extends OMToolComponent implements Observer {
private JFrame frame = null;
private AnimalLayer animalLayer = null;
private Controller controller;
/**
* Tool interface method. The retrieval tool's interface. This
* method creates a button that will bring up the BeanPanel.
*
* @return A container that will contain the 'face' of this panel
* on the OpenMap ToolPanel.
*/
public Container getFace() {
JButton button = null;
if (getUseAsTool()) {
button = new JButton(new ImageIcon("share/img/kalender.gif"));
button.setBorderPainted(false);
button.setToolTipText("Open TimeLine");
button.setMargin(new Insets(0, 0, 0, 0));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Opening MyComponent");
display();
}
});
}
return button;
}
/**
* Get the ActionListener that triggers the LayersPanel. Useful to have to
* provide an alternative way to bring up the LayersPanel.
*
* @return ActionListener
*/
private synchronized void display() {
if (frame == null) {
frame = new JFrame("Timeline");
JPanel panel = new TimelineView(controller);
frame.add(panel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.out.println("Closing MyComponent");
frame.setVisible(false);
}
});
frame.pack();
}
frame.setVisible(true);
}
/**
* Called when the BeanPanel is added the BeanContext, or when
* another object is added to the BeanContext after the
* LayerHandler has been added. This allows the BeanPanel to keep
* up-to-date with any objects that it may be interested in,
* namely, the LayerHandler. If a LayerHandler has already been
* added, the new LayerHandler will replace it.
*
* @param someObj the object being added to the BeanContext.
*/
public void findAndInit(Object someObj) {
if (someObj instanceof AnimalLayer) {
System.out.println("Registering animal layer in MyComponent.");
this.animalLayer = (AnimalLayer)someObj;
}
}
public void update(Observable o, Object arg) {
// TODO Auto-generated method stub
// data should be coming from the controller
}
}
| Java |
/*
* TimeLabelPanel.java
*
* Created on July 11, 2008, 2:26 AM
*/
package anivis.ui.timeline;
import anivis.base.TimeInterval;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import prefuse.util.TimeLib;
/**
*
* @author urp
*/
public class TimeLabelPanel extends javax.swing.JPanel
{
public static int minLabelDist=50;
private TimeInterval timeSpan=new TimeInterval();
/** Creates new form TimeLabelPanel */
public TimeLabelPanel()
{
initComponents();
timeSpan = new TimeInterval( (new GregorianCalendar(1900,1,1)).getTime(),
(new GregorianCalendar(2000,1,1)).getTime() );
}
public TimeInterval getTimeSpan()
{
return timeSpan;
}
public void setTimeSpan(TimeInterval interval)
{
timeSpan = interval;
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(0,0,getWidth(),getHeight());
int maxLabels = getWidth()/ minLabelDist;
GregorianCalendar curCalendar = new GregorianCalendar();
curCalendar.setTime(timeSpan.getBegin());
Date beginDate = timeSpan.getBegin();
Date endDate = timeSpan.getEnd();
long timeLength= timeSpan.getLengthInMillis();
//find weather to show year, month or date labels
int field=Calendar.DATE;
long fieldLength = timeSpan.getLength(Calendar.YEAR);
if(fieldLength>1)
{
TimeLib.clearTo(curCalendar,Calendar.MONTH);
field = Calendar.YEAR;
}
else
{ fieldLength = timeSpan.getLength(Calendar.MONTH);
if(fieldLength>1)
{
TimeLib.clearTo(curCalendar,Calendar.DATE);
field = Calendar.MONTH;
}
else
{ fieldLength = timeSpan.getLength(Calendar.DATE);
if(fieldLength>1)
{
TimeLib.clearTo(curCalendar,Calendar.HOUR);
field = Calendar.DATE;
}
}
}
int increment = 1;
while( fieldLength/increment > maxLabels )
increment++;
while(curCalendar.before(timeSpan.getEnd()))
{
TimeLib.increment(curCalendar, field, increment);
float pos = getWidth() / ((float)timeLength) * ( (float)(curCalendar.getTimeInMillis()-beginDate.getTime()) );
System.out.println(pos);
g2d.drawString("MARK", pos, 10);
g2d.drawLine((int) pos, 30,(int) pos, 40);
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
setName("Form"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 785, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(0, 95, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.ui;
import anivis.base.Notification;
import anivis.base.RestrictionNotification;
import anivis.db.QueryLayer;
import anivis.db.QueryLayer.RestrictionType;
import anivis.layers.Layer;
import anivis.layers.ObservationLayer;
import java.sql.SQLException;
import java.util.GregorianCalendar;
import java.util.Observable;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import prefuse.data.Table;
/**
*
* @author urp
*/
public class Controller extends java.util.Observable implements java.util.Observer
{
private QueryLayer queryLayers;
private ObservationLayer layers;
public Controller()
{
try {
queryLayers=new QueryLayer();
queryLayers.addObserver(this);
GregorianCalendar high = new GregorianCalendar();
GregorianCalendar low = new GregorianCalendar(1900, GregorianCalendar.JANUARY, 1);
setRestriction(new QueryLayer.RangeRestriction(low.getTimeInMillis() / 1000.0, high.getTimeInMillis() / 1000.0, RestrictionType.TimeWindow));
}
catch (java.sql.SQLException sqle) {
System.err.println(sqle);
}
catch (ClassNotFoundException cnfe) {
System.err.println(cnfe);
}
}
public QueryLayer getQueryLayer() {
return queryLayers;
}
public Table getTable(Set<RestrictionType> r)
{
Table table = null;
try
{
table = queryLayers.getData(r);
System.out.println("CONTROLLER.getTable: " + table.getRowCount());
} catch (SQLException ex)
{
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
System.err.println(ex);
}
return table;
}
public boolean setRestriction(QueryLayer.Restriction r)
{
System.out.println("CONTROLLER.setRestriction: " + r);
boolean returnValue = queryLayers.setRestriction(r);
setChanged();
notifyObservers(new RestrictionNotification(r));
return returnValue;
}
public boolean clearRestriction(QueryLayer.RestrictionType t)
{
return queryLayers.clearRestriction(t);
}
public void update(Observable o, Object arg)
{
System.out.println("CONTROLLER.update: " + arg);
setChanged();
notifyObservers(arg);
}
public void prepareData()
{
System.out.println("CONTROLLER.prepareData");
try {
queryLayers.prepareData();
}
catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
| Java |
package anivis.ui.map;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Paint;
import anivis.AniVisApp;
import anivis.base.DataAvailableNotification;
import anivis.base.Notification;
import anivis.base.RestrictionNotification;
import anivis.db.QueryLayer;
import anivis.db.QueryLayer.Restriction;
import anivis.db.QueryLayer.RestrictionType;
import anivis.layers.ObservationLayer;
import anivis.ui.Controller;
import com.bbn.openmap.Layer;
import com.bbn.openmap.event.ProjectionEvent;
import com.bbn.openmap.omGraphics.OMCircle;
import com.bbn.openmap.omGraphics.OMGraphic;
import com.bbn.openmap.omGraphics.OMGraphicList;
import com.bbn.openmap.omGraphics.OMLine;
import com.bbn.openmap.omGraphics.OMPoint;
import com.bbn.openmap.proj.Projection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Iterator;
import java.util.Observable;
import java.util.Observer;
import java.util.Set;
import prefuse.data.Table;
import prefuse.data.Tuple;
import prefuse.data.tuple.TableTuple;
import com.bbn.openmap.LatLonPoint;
public class AnimalLayer extends Layer implements Observer {
/**
* A list of graphics to be painted on the map.
*/
private ObservationLayer layer;
private OMGraphicList omgraphics;
private boolean waitsForData = true;
/**
* Construct a default route layer. Initializes omgraphics to a
* new OMGraphicList, and invokes createGraphics to create the
* canned list of routes.
*/
public AnimalLayer() {
omgraphics = new OMGraphicList();
// register
layer = new ObservationLayer("Avian Network",true,true);
HashSet<RestrictionType> r = new HashSet<RestrictionType>();
r.add(RestrictionType.Longitude);
r.add(RestrictionType.Latitude);
r.add(RestrictionType.TimeWindow);
r.add(RestrictionType.SpatialAggregation);
layer.setRestrictionTypes(r);
AniVisApp.getApplication().getController().addObserver(this);
createGraphics(omgraphics);
}
/**
* Clears and then fills the given OMGraphicList. Creates three
* lines for display on the map.
*
* @param graphics The OMGraphicList to clear and populate
* @return the graphics list, after being cleared and filled
*/
public synchronized OMGraphicList createGraphics(OMGraphicList graphics) {
System.out.println("Repainting animal layer.");
omgraphics.clear();
// fill color
Color fillColor = new Color(0.85f, 0.18f, 0.15f, 0.05f);
Table table = layer.getTable();
synchronized(table) {
System.out.println("AnimalLayer got: " + table.getRowCount());
int latitudeIndex = table.getColumnNumber("latitude");
int longitudeIndex = table.getColumnNumber("longitude");
int aggregationIndex = table.getColumnNumber("aggregation");
for (int i = 1; table.isValidRow(i); i++) {
Tuple tuple = table.getTuple(i);
OMPoint omPoint = new OMPoint(tuple.getFloat(latitudeIndex), tuple.getFloat(longitudeIndex), 1);
//OMCircle omCircle = new OMCircle(tuple.getFloat(latitudeIndex), tuple.getFloat(longitudeIndex), 0.25f);
//omCircle.setLinePaint(linePaint);
//omCircle.setLinePaint()(new Color(1.0f, 0, 0));
omPoint.setLineColor(fillColor);
//omCircle.setFillPaint(fillColor);
//graphics.addOMGraphic(omCircle);
graphics.addOMGraphic(omPoint);
}
}
return graphics;
}
//----------------------------------------------------------------------
// Layer overrides
//----------------------------------------------------------------------
/**
* Renders the graphics list. It is important to make this routine
* as fast as possible since it is called frequently by Swing, and
* the User Interface blocks while painting is done.
*/
public void paint(java.awt.Graphics g) {
omgraphics.render(g);
}
//----------------------------------------------------------------------
// ProjectionListener interface implementation
//----------------------------------------------------------------------
/**
* Handler for <code>ProjectionEvent</code>s. This function is
* invoked when the <code>MapBean</code> projection changes. The
* graphics are reprojected and then the Layer is repainted.
* <p>
*
* @param e the projection event
*/
public void projectionChanged(ProjectionEvent e) {
System.out.println(e.getProjection().getUpperLeft() + " " + e.getProjection().getLowerRight());
// TODO: call the controller and set the restrictions based on the current visualization of the map (corners)
// call the controller
Controller controller = AniVisApp.getApplication().getController();
LatLonPoint upperLeft = e.getProjection().getUpperLeft();
LatLonPoint lowerRight = e.getProjection().getLowerRight();
QueryLayer.RangeRestriction longitudeRestriction = new QueryLayer.RangeRestriction(upperLeft.getLongitude(), lowerRight.getLongitude(), RestrictionType.Longitude);
QueryLayer.RangeRestriction latitudeRestriction = new QueryLayer.RangeRestriction(lowerRight.getLatitude(), upperLeft.getLatitude(), RestrictionType.Latitude);
QueryLayer.Aggregation aggregation = new QueryLayer.Aggregation(1, QueryLayer.RestrictionType.SpatialAggregation);
controller.setRestriction(longitudeRestriction);
controller.setRestriction(latitudeRestriction);
controller.setRestriction(aggregation);
// prepare data
controller.prepareData();
omgraphics.project(e.getProjection(), true);
repaint();
}
public synchronized void update(Observable sender, Object message)
{
System.out.println("AnimalLayer.update " + message);
Notification notification = (Notification) message;
if(notification.isRestrictionNotification())
{
RestrictionNotification n = (RestrictionNotification) notification;
if( layer.getRestrictionTypes().contains( n.getRestriction().getType() ) )
{ waitsForData = true; }
}
else
if(notification.isDataAvaialableNotification())
{
DataAvailableNotification n = (DataAvailableNotification) notification;
Set<RestrictionType> rT = n.getRestrictionTypes();
if(waitsForData/* && rT.contains(layer.getRestrictionTypes())*/)
{ /*get data*/
anivis.ui.Controller c = (Controller) sender;
// prepare the data
layer.getData(c);
// draw the points
createGraphics(omgraphics);
// repaint our graphics
repaint();
waitsForData = false;
}
}
}
}
| Java |
package anivis.ui.map;
import com.bbn.openmap.MapBean;
/**
* A sample application incorporating the <code>MapHandler</code>
* and <code>MapBean</code>.
* <p>
* Uses a properties file to configure the layers.
*/
public class MapView extends MapBean {
// the functionality of this class lives in MapBean completely
} | Java |
// **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/app/OpenMap.java,v $
// $RCSfile: OpenMap.java,v $
// $Revision: 1.11.2.4 $
// $Date: 2008/01/25 17:44:27 $
// $Author: dietrick $
//
// **********************************************************************
package anivis.ui.map;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import com.bbn.openmap.MapHandler;
import com.bbn.openmap.PropertyHandler;
import com.bbn.openmap.gui.BasicMapPanel;
import com.bbn.openmap.gui.MapPanel;
import com.bbn.openmap.gui.OpenMapFrame;
import com.bbn.openmap.util.ArgParser;
import com.bbn.openmap.util.Debug;
/**
* The OpenMap application framework. This class creates a PropertyHandler that
* searches the classpath, config directory and user's home directory for an
* openmap.properties file, and creates the application based on the contents of
* the properties files. It also creates an MapPanel and an OpenMapFrame to be
* used for the application and adds them to the MapHandler contained in the
* MapPanel. All other components are added to that MapHandler as well, and they
* use the MapHandler to locate, connect and communicate with each other.
*/
public class MapViewPropertyHandler {
protected MapPanel mapPanel;
/**
* Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame,
* and brings up the layer palettes that are being told to be open at
* startup. The MapPanel will create a PropertiesHandler that will search
* for an openmap.properties file.
*/
public MapViewPropertyHandler() {
this(null);
}
/**
* Create a new OpenMap framework object - creates a MapPanel, OpenMapFrame,
* and brings up the layer palettes that are being told to be open at
* startup. The properties in the PropertyHandler will be used to configure
* the application. PropertyHandler may be null.
*/
public MapViewPropertyHandler(PropertyHandler propertyHandler) {
mapPanel = new BasicMapPanel(propertyHandler, true);
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// TODO There's something going on here with the progress
// reporter and the swing thread that is causing the app to hang
// in Leopard.
showInFrame();
}
});
}
protected void showInFrame() {
((BasicMapPanel)mapPanel).create();
OpenMapFrame omf = new OpenMapFrame();
setWindowListenerOnFrame(omf);
getMapHandler().add(omf);
omf.setVisible(true);
mapPanel.getMapBean().showLayerPalettes();
Debug.message("basic", "OpenMap: READY");
}
/**
* A method called internally to set the WindowListener behavior on an OpenMapFrame
* used for the OpenMap application. By default, this method adds a
* WindowAdapter that calls System.exit(0), killing java. You can extend
* this to add a WindowListener to the OpenMapFrame that does nothing or
* something else.
*/
protected void setWindowListenerOnFrame(OpenMapFrame omf) {
omf.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
/**
* Get the MapHandler used for the OpenMap object.
*/
public MapHandler getMapHandler() {
return mapPanel.getMapHandler();
}
/**
* Get the MapPanel, the container for the OpenMap components.
*/
public MapPanel getMapPanel() {
return mapPanel;
}
/**
* Create and return an OpenMap object that uses a standard PropertyHandler
* to configure itself. The OpenMap object has a MapHandler that you can use
* to gain access to all the components.
*
* @return OpenMap
* @see #getMapHandler
*/
public static MapViewPropertyHandler create() {
return new MapViewPropertyHandler(null);
}
/**
* Create and return an OpenMap object that uses a standard PropertyHandler
* to configure itself. The OpenMap object has a MapHandler that you can use
* to gain access to all the components.
*
* @return OpenMap
* @see #getMapHandler
*/
public static MapViewPropertyHandler create(String propertiesFile) {
Debug.init();
PropertyHandler propertyHandler = null;
if (propertiesFile != null) {
try {
propertyHandler = new PropertyHandler(propertiesFile);
} catch (MalformedURLException murle) {
Debug.error(murle.getMessage());
murle.printStackTrace();
propertyHandler = null;
} catch (IOException ioe) {
Debug.error(ioe.getMessage());
ioe.printStackTrace();
propertyHandler = null;
}
}
return new MapViewPropertyHandler(propertyHandler);
}
/**
* The main OpenMap application.
*/
static public void main(String args[]) {
ArgParser ap = new ArgParser("OpenMap");
String propArgs = null;
ap.add("properties",
"A resource, file path or URL to properties file\n Ex: http://myhost.com/xyz.props or file:/myhome/abc.pro\n See Java Documentation for java.net.URL class for more details",
1);
ap.parse(args);
String[] arg = ap.getArgValues("properties");
if (arg != null) {
propArgs = arg[0];
}
if (propArgs == null) {
propArgs = "AniVis.properties";
}
MapViewPropertyHandler.create(propArgs);
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.base;
import java.util.Date;
import java.util.GregorianCalendar;
import prefuse.util.TimeLib;
/**
*
* @author urp
*/
public class TimeInterval {
private Date begin;
private Date end;
public TimeInterval()
{
begin = new GregorianCalendar(2000,1,1).getTime();
end = new GregorianCalendar(1900,1,1).getTime();
}
public TimeInterval(Date aBegin,Date anEnd)
{
begin = aBegin;
end = anEnd;
}
public long getBeginTime()
{
return begin.getTime();
}
public long getEndTime()
{
return end.getTime();
}
public Date getBegin()
{
return begin;
}
public Date getEnd()
{
return end;
}
public boolean isValid()
{
return !begin.after(end);
}
public boolean contains(Date date)
{
return date.after(begin) && date.before(end);
}
public long getLength(int field)
{
return TimeLib.getUnitsBetween(begin.getTime(), end.getTime(), field);
}
public long getLengthInMillis()
{
return end.getTime()-begin.getTime();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.base;
import anivis.db.QueryLayer.RestrictionType;
import java.util.Set;
/**
*
* @author urp
*/
public class DataAvailableNotification implements Notification
{
Set<RestrictionType> restrictionTypes;
public DataAvailableNotification(Set<RestrictionType> r)
{
restrictionTypes = r;
}
public boolean isDataAvaialableNotification()
{
return true;
}
public boolean isRestrictionNotification()
{
return false;
}
public Set<RestrictionType> getRestrictionTypes()
{
return restrictionTypes;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.base;
import anivis.db.QueryLayer.Restriction;
/**
*
* @author urp
*/
public class RestrictionNotification implements Notification
{
public Restriction restriction;
public RestrictionNotification(Restriction restriction)
{
this.restriction = restriction;
}
public Restriction getRestriction()
{
return restriction;
}
public boolean isDataAvaialableNotification()
{
return false;
}
public boolean isRestrictionNotification()
{
return true;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.base;
/**
*
* @author urp
*/
public interface Notification {
public abstract boolean isDataAvaialableNotification();
public abstract boolean isRestrictionNotification();
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.layers;
/**
*
* @author urp
*/
public class ObservationTuple extends prefuse.data.tuple.TableTuple
{
public double getLattitude() {
return super.getDouble("latitude");
}
public double getLoungitude() {
return super.getDouble("longitude");
}
public int getAggregationLevel() {
return super.getInt("aggregation");
}
public int getSpeciesId() {
return super.getInt("species_id");
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.layers;
import anivis.ui.Controller;
import prefuse.data.Table;
/**
*
* @author urp
*/
public class ObservationLayer extends Layer
{
private Table table;
public ObservationLayer(String layerName,boolean mapVisibility,boolean timelineVisibility)
{
super(layerName,mapVisibility,timelineVisibility);
table = new Table();
}
public ObservationLayer(Table aTable,String layerName,boolean mapVisibility,boolean timelineVisibility)
{
super(layerName,mapVisibility,timelineVisibility);
table = aTable;
}
public void getData(Controller c)
{
table = c.getTable(super.getRestrictionTypes());
System.out.println("Layer got " + table.getRowCount());
}
public Table getTable()
{
return table;
}
public void setTable(Table newTable)
{
table = newTable;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package anivis.layers;
import java.util.Set;
import anivis.db.QueryLayer.Restriction;
import anivis.db.QueryLayer.RestrictionType;
import anivis.ui.Controller;
/**
*
* @author urp
*/
public abstract class Layer
{
private String name;
private Set<RestrictionType> restrictions;
private boolean mapVisibility=true;
private boolean tlVisibility=true;
public Layer(String aName,boolean map,boolean timeline)
{
name = aName;
mapVisibility = map;
tlVisibility = timeline;
}
public Set<RestrictionType> getRestrictionTypes()
{
return restrictions;
}
public void setRestrictionTypes(Set<RestrictionType> r)
{
restrictions = r;
}
public String getName()
{ return name; }
public void setName(String newName)
{ name = newName; }
public boolean getMapVisibility() {
return mapVisibility;
}
public boolean getTimelineVisibility() {
return tlVisibility;
}
public void setMapVisibility(boolean visibility) {
mapVisibility = visibility;
}
public void setTimelineVisibility(boolean visibility) {
tlVisibility = visibility;
}
public abstract void getData(Controller c);
}
| Java |
/*
* AniVisAboutBox.java
*/
package anivis;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import org.jdesktop.application.Action;
public class AniVisAboutBox extends javax.swing.JDialog {
public AniVisAboutBox(java.awt.Frame parent) {
super(parent);
initComponents();
getRootPane().setDefaultButton(closeButton);
}
@Action public void closeAboutBox() {
setVisible(false);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
closeButton = new javax.swing.JButton("Close");
javax.swing.JLabel appTitleLabel = new javax.swing.JLabel();
javax.swing.JLabel versionLabel = new javax.swing.JLabel();
javax.swing.JLabel appVersionLabel = new javax.swing.JLabel();
javax.swing.JLabel vendorLabel = new javax.swing.JLabel();
javax.swing.JLabel appVendorLabel = new javax.swing.JLabel();
javax.swing.JLabel homepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel();
javax.swing.JLabel appDescLabel = new javax.swing.JLabel();
javax.swing.JLabel imageLabel = new javax.swing.JLabel();
// application
AniVisApp app = AniVisApp.getApplication();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle(app.getString("title")); // NOI18N
setModal(true);
setName("aboutBox"); // NOI18N
setResizable(false);
closeButton.setName("closeButton"); // NOI18N
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
AniVisAboutBox.this.closeAboutBox();
}
});
appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4));
appTitleLabel.setText(app.getString("Application.title")); // NOI18N
appTitleLabel.setName("appTitleLabel"); // NOI18N
versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD));
versionLabel.setText(app.getString("versionLabel.text")); // NOI18N
versionLabel.setName("versionLabel"); // NOI18N
appVersionLabel.setText(app.getString("Application.version")); // NOI18N
appVersionLabel.setName("appVersionLabel"); // NOI18N
vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD));
vendorLabel.setText(app.getString("vendorLabel.text")); // NOI18N
vendorLabel.setName("vendorLabel"); // NOI18N
appVendorLabel.setText(app.getString("Application.vendor")); // NOI18N
appVendorLabel.setName("appVendorLabel"); // NOI18N
homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD));
homepageLabel.setText(app.getString("homepageLabel.text")); // NOI18N
homepageLabel.setName("homepageLabel"); // NOI18N
appHomepageLabel.setText(app.getString("Application.homepage")); // NOI18N
appHomepageLabel.setName("appHomepageLabel"); // NOI18N
appDescLabel.setText(app.getString("appDescLabel.text")); // NOI18N
appDescLabel.setName("appDescLabel"); // NOI18N
imageLabel.setIcon(new ImageIcon(app.getString("imageLabel.icon"))); // NOI18N
imageLabel.setName("imageLabel"); // NOI18N
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(imageLabel)
.add(18, 18, 18)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
.add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(versionLabel)
.add(vendorLabel)
.add(homepageLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(appVersionLabel)
.add(appVendorLabel)
.add(appHomepageLabel)))
.add(org.jdesktop.layout.GroupLayout.LEADING, appTitleLabel)
.add(org.jdesktop.layout.GroupLayout.LEADING, appDescLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 266, Short.MAX_VALUE)
.add(closeButton))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(imageLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(appTitleLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(appDescLabel)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(versionLabel)
.add(appVersionLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(vendorLabel)
.add(appVendorLabel))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(homepageLabel)
.add(appHomepageLabel))
.add(19, 19, Short.MAX_VALUE)
.add(closeButton)
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton closeButton;
// End of variables declaration//GEN-END:variables
}
| Java |
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import nl.captcha.*;
import nl.captcha.servlet.*;
import nl.captcha.backgrounds.*;
import nl.captcha.text.producer.*;
public class MyCaptchaServlet extends SimpleCaptchaServlet
{
@Override
//one change done by me.
//second change done by me.
//Third change done by me
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
char str[]=new char[62];
for(int i=97;i<123;i++)
str[i-97]=(char)i;
for(int i=65;i<91;i++)
str[26+i-65]=(char)i;
for(int i=48;i<58;i++)
str[52+i-48]=(char)i;
Captcha captcha = new Captcha.Builder(250,40).addText(new DefaultTextProducer(8,str)).addBorder().gimp().addBackground(new GradiatedBackgroundProducer()).addNoise().build();
CaptchaServletUtil.writeImage(response, captcha.getImage());
request.getSession().setAttribute(Captcha.NAME, captcha);
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.VenueActivity;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueActivityInstrumentationTestCase extends
ActivityInstrumentationTestCase2<VenueActivity> {
public VenueActivityInstrumentationTestCase() {
super("com.joelapenna.foursquared", VenueActivity.class);
}
@SmallTest
public void testOnCreate() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450");
setActivityIntent(intent);
VenueActivity activity = getActivity();
activity.openOptionsMenu();
activity.closeOptionsMenu();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareCredentialsException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareCredentialsException(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareError extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareError(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareParseException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareParseException(String message) {
super(message);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareException extends Exception {
private static final long serialVersionUID = 1L;
private String mExtra;
public FoursquareException(String message) {
super(message);
}
public FoursquareException(String message, String extra) {
super(message);
mExtra = extra;
}
public String getExtra() {
return mExtra;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.http.AbstractHttpApi;
import com.joelapenna.foursquare.http.HttpApi;
import com.joelapenna.foursquare.http.HttpApiWithBasicAuth;
import com.joelapenna.foursquare.http.HttpApiWithOAuth;
import com.joelapenna.foursquare.parsers.json.CategoryParser;
import com.joelapenna.foursquare.parsers.json.CheckinParser;
import com.joelapenna.foursquare.parsers.json.CheckinResultParser;
import com.joelapenna.foursquare.parsers.json.CityParser;
import com.joelapenna.foursquare.parsers.json.CredentialsParser;
import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser;
import com.joelapenna.foursquare.parsers.json.GroupParser;
import com.joelapenna.foursquare.parsers.json.ResponseParser;
import com.joelapenna.foursquare.parsers.json.SettingsParser;
import com.joelapenna.foursquare.parsers.json.TipParser;
import com.joelapenna.foursquare.parsers.json.TodoParser;
import com.joelapenna.foursquare.parsers.json.UserParser;
import com.joelapenna.foursquare.parsers.json.VenueParser;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.City;
import com.joelapenna.foursquare.types.Credentials;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.JSONUtils;
import com.joelapenna.foursquared.util.Base64Coder;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class FoursquareHttpApiV1 {
private static final Logger LOG = Logger
.getLogger(FoursquareHttpApiV1.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.DEBUG;
private static final String DATATYPE = ".json";
private static final String URL_API_AUTHEXCHANGE = "/authexchange";
private static final String URL_API_ADDVENUE = "/addvenue";
private static final String URL_API_ADDTIP = "/addtip";
private static final String URL_API_CITIES = "/cities";
private static final String URL_API_CHECKINS = "/checkins";
private static final String URL_API_CHECKIN = "/checkin";
private static final String URL_API_USER = "/user";
private static final String URL_API_VENUE = "/venue";
private static final String URL_API_VENUES = "/venues";
private static final String URL_API_TIPS = "/tips";
private static final String URL_API_TODOS = "/todos";
private static final String URL_API_FRIEND_REQUESTS = "/friend/requests";
private static final String URL_API_FRIEND_APPROVE = "/friend/approve";
private static final String URL_API_FRIEND_DENY = "/friend/deny";
private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest";
private static final String URL_API_FRIENDS = "/friends";
private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname";
private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone";
private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook";
private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter";
private static final String URL_API_CATEGORIES = "/categories";
private static final String URL_API_HISTORY = "/history";
private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail";
private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail";
private static final String URL_API_SETPINGS = "/settings/setpings";
private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed";
private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated";
private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate";
private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit";
private static final String URL_API_USER_UPDATE = "/user/update";
private static final String URL_API_MARK_TODO = "/mark/todo";
private static final String URL_API_MARK_IGNORE = "/mark/ignore";
private static final String URL_API_MARK_DONE = "/mark/done";
private static final String URL_API_UNMARK_TODO = "/unmark/todo";
private static final String URL_API_UNMARK_DONE = "/unmark/done";
private static final String URL_API_TIP_DETAIL = "/tip/detail";
private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient();
private HttpApi mHttpApi;
private final String mApiBaseUrl;
private final AuthScope mAuthScope;
public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) {
mApiBaseUrl = "https://" + domain + "/v1";
mAuthScope = new AuthScope(domain, 80);
if (useOAuth) {
mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion);
} else {
mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion);
}
}
void setCredentials(String phone, String password) {
if (phone == null || phone.length() == 0 || password == null || password.length() == 0) {
if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials");
mHttpClient.getCredentialsProvider().clear();
} else {
if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******");
mHttpClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(phone, password));
}
}
public boolean hasCredentials() {
return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null;
}
public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) {
if (DEBUG) {
LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " "
+ oAuthConsumerSecret);
}
((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey,
oAuthConsumerSecret);
}
public void setOAuthTokenWithSecret(String token, String secret) {
if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret);
((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret);
}
public boolean hasOAuthTokenWithSecret() {
return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret();
}
/*
* /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec...
* 18
*/
public Credentials authExchange(String phone, String password) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) {
throw new IllegalStateException("Cannot do authExchange with OAuthToken already set");
}
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), //
new BasicNameValuePair("fs_username", phone), //
new BasicNameValuePair("fs_password", password));
return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser());
}
/*
* /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip")
*/
Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("text", text), //
new BasicNameValuePair("type", type), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* @param name the name of the venue
* @param address the address of the venue (e.g., "202 1st Avenue")
* @param crossstreet the cross streets (e.g., "btw Grand & Broome")
* @param city the city name where this venue is
* @param state the state where the city is
* @param zip (optional) the ZIP code for the venue
* @param phone (optional) the phone number for the venue
* @return
* @throws FoursquareException
* @throws FoursquareCredentialsException
* @throws FoursquareError
* @throws IOException
*/
Venue addvenue(String name, String address, String crossstreet, String city, String state,
String zip, String phone, String categoryId, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser());
}
/*
* /cities
*/
@SuppressWarnings("unchecked")
Group<City> cities() throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES));
return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser()));
}
/*
* /checkins?
*/
@SuppressWarnings("unchecked")
Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet,
new GroupParser(new CheckinParser()));
}
/*
* /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1
*/
CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc,
String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers,
boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("venue", venue), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("shout", shout), //
new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), //
new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), //
new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), //
new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), //
new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'.
return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser());
}
/**
* /user?uid=9937
*/
User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong,
String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), //
new BasicNameValuePair("badges", (badges) ? "1" : "0"), //
new BasicNameValuePair("stats", (stats) ? "1" : "0"), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (User) mHttpApi.doHttpRequest(httpGet, new UserParser());
}
/**
* /venues?geolat=37.770900&geolong=-122.43698
*/
@SuppressWarnings("unchecked")
Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String query, int limit) throws FoursquareException, FoursquareError,
IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("q", query), //
new BasicNameValuePair("l", String.valueOf(limit)));
return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new GroupParser(new VenueParser())));
}
/**
* /venue?vid=1234
*/
Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser());
}
/**
* /tips?geolat=37.770900&geolong=-122.436987&l=1
*/
@SuppressWarnings("unchecked")
Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("filter", filter), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TipParser()));
}
/**
* /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby]
*/
@SuppressWarnings("unchecked")
Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt, boolean recent, boolean nearby, int limit)
throws FoursquareException, FoursquareError, IOException {
String sort = null;
if (recent) {
sort = "recent";
} else if (nearby) {
sort = "nearby";
}
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TodoParser()));
}
/*
* /friends?uid=9937
*/
@SuppressWarnings("unchecked")
Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/requests
*/
@SuppressWarnings("unchecked")
Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/approve?uid=9937
*/
User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/deny?uid=9937
*/
User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/sendrequest?uid=9937
*/
User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/**
* /findfriends/byname?q=john doe, mary smith
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByName(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /findfriends/byphone?q=555-5555,555-5556
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByPhone(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/byfacebook?q=friendid,friendid,friendid
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByFacebook(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/bytwitter?q=yourtwittername
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByTwitter(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /categories
*/
@SuppressWarnings("unchecked")
public Group<Category> categories() throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES));
return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser()));
}
/**
* /history
*/
@SuppressWarnings("unchecked")
public Group<Checkin> history(String limit, String sinceid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY),
new BasicNameValuePair("l", limit),
new BasicNameValuePair("sinceid", sinceid));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser()));
}
/**
* /mark/todo
*/
public Todo markTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* This is a hacky special case, hopefully the api will be updated in v2 for this.
* /mark/todo
*/
public Todo markTodoVenue(String vid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("vid", vid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* /mark/ignore
*/
public Tip markIgnore(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /mark/done
*/
public Tip markDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/todo
*/
public Tip unmarkTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/done
*/
public Tip unmarkDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /tip/detail?tid=1234
*/
public Tip tipDetail(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser());
}
/**
* /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails
*/
public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), //
new BasicNameValuePair("p", phones),
new BasicNameValuePair("e", emails));
return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser());
}
/**
* /invite/byemail?q=comma-sep-list-of-emails
*/
public Response inviteByEmail(String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), //
new BasicNameValuePair("q", emails));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /settings/setpings?self=[on|off]
*/
public Settings setpings(boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair("self", on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /settings/setpings?uid=userid
*/
public Settings setpings(String userid, boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair(userid, on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /venue/flagclosed?vid=venueid
*/
public Response flagclosed(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagmislocated?vid=venueid
*/
public Response flagmislocated(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagduplicate?vid=venueid
*/
public Response flagduplicate(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/prposeedit?vid=venueid&name=...
*/
public Response proposeedit(String venueId, String name, String address, String crossstreet,
String city, String state, String zip, String phone, String categoryId, String geolat,
String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), //
new BasicNameValuePair("vid", venueId), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
private String fullUrl(String url) {
return mApiBaseUrl + url + DATATYPE;
}
/**
* /user/update
* Need to bring this method under control like the rest of the api methods. Leaving it
* in this state as authorization will probably switch from basic auth in the near future
* anyway, will have to be updated. Also unlike the other methods, we're sending up data
* which aren't basic name/value pairs.
*/
public User userUpdate(String imagePathToJpg, String username, String password)
throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException {
String BOUNDARY = "------------------319831265358979362846";
String lineEnd = "\r\n";
String twoHyphens = "--";
int maxBufferSize = 8192;
File file = new File(imagePathToJpg);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(fullUrl(URL_API_USER_UPDATE));
HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY);
conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password));
// We are always saving the image to a jpg so we can use .jpg as the extension below.
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + BOUNDARY + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd);
dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int totalBytesRead = bytesRead;
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesRead = totalBytesRead + bytesRead;
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine = "";
while ((responseLine = in.readLine()) != null) {
response.append(responseLine);
}
in.close();
try {
return (User)JSONUtils.consume(new UserParser(), response.toString());
} catch (Exception ex) {
throw new FoursquareParseException(
"Error parsing user photo upload response, invalid json.");
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface HttpApi {
abstract public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException;
abstract public String doHttpPost(String url, NameValuePair... nameValuePairs)
throws FoursquareCredentialsException, FoursquareParseException, FoursquareException,
IOException;
abstract public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs);
abstract public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs);
abstract public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary)
throws IOException;
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.signature.SignatureMethod;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class HttpApiWithOAuth extends AbstractHttpApi {
protected static final Logger LOG = Logger.getLogger(HttpApiWithOAuth.class.getCanonicalName());
protected static final boolean DEBUG = Foursquare.DEBUG;
private OAuthConsumer mConsumer;
public HttpApiWithOAuth(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
try {
if (DEBUG) LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI());
if (DEBUG) LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", "
+ mConsumer.getConsumerSecret());
if (DEBUG) LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", "
+ mConsumer.getTokenSecret());
mConsumer.sign(httpRequest);
} catch (OAuthMessageSignerException e) {
if (DEBUG) LOG.log(Level.FINE, "OAuthMessageSignerException", e);
throw new RuntimeException(e);
} catch (OAuthExpectationFailedException e) {
if (DEBUG) LOG.log(Level.FINE, "OAuthExpectationFailedException", e);
throw new RuntimeException(e);
}
return executeHttpRequest(httpRequest, parser);
}
public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareError,
FoursquareParseException, IOException, FoursquareCredentialsException {
throw new RuntimeException("Haven't written this method yet.");
}
public void setOAuthConsumerCredentials(String key, String secret) {
mConsumer = new CommonsHttpOAuthConsumer(key, secret, SignatureMethod.HMAC_SHA1);
}
public void setOAuthTokenWithSecret(String token, String tokenSecret) {
verifyConsumer();
if (token == null && tokenSecret == null) {
if (DEBUG) LOG.log(Level.FINE, "Resetting consumer due to null token/secret.");
String consumerKey = mConsumer.getConsumerKey();
String consumerSecret = mConsumer.getConsumerSecret();
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret,
SignatureMethod.HMAC_SHA1);
} else {
mConsumer.setTokenWithSecret(token, tokenSecret);
}
}
public boolean hasOAuthTokenWithSecret() {
verifyConsumer();
return (mConsumer.getToken() != null) && (mConsumer.getTokenSecret() != null);
}
private void verifyConsumer() {
if (mConsumer == null) {
throw new IllegalStateException(
"Cannot call method without setting consumer credentials.");
}
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class HttpApiWithBasicAuth extends AbstractHttpApi {
private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider)context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
// If not auth scheme has been initialized yet
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
// Obtain credentials matching the target host
org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
// If found, generate BasicScheme preemptively
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
httpClient.addRequestInterceptor(preemptiveAuth, 0);
}
public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
return executeHttpRequest(httpRequest, parser);
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.util.JSONUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract public class AbstractHttpApi implements HttpApi {
protected static final Logger LOG = Logger.getLogger(AbstractHttpApi.class.getCanonicalName());
protected static final boolean DEBUG = Foursquare.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.joelapenna.foursquare";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
public FoursquareType executeHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
HttpResponse response = executeHttpRequest(httpRequest);
if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: "
+ httpRequest.getURI().toString());
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case 200:
String content = EntityUtils.toString(response.getEntity());
return JSONUtils.consume(parser, content);
case 400:
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 400");
throw new FoursquareException(
response.getStatusLine().toString(),
EntityUtils.toString(response.getEntity()));
case 401:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 401");
throw new FoursquareCredentialsException(response.getStatusLine().toString());
case 404:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 404");
throw new FoursquareException(response.getStatusLine().toString());
case 500:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 500");
throw new FoursquareException("Foursquare is down. Try again later.");
default:
if (DEBUG) LOG.log(Level.FINE, "Default case for status code reached: "
+ response.getStatusLine().toString());
response.getEntity().consumeContent();
throw new FoursquareException("Error connecting to Foursquare: " + statusCode + ". Try again later.");
}
}
public String doHttpPost(String url, NameValuePair... nameValuePairs)
throws FoursquareCredentialsException, FoursquareParseException, FoursquareException,
IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpPost: " + url);
HttpPost httpPost = createHttpPost(url, nameValuePairs);
HttpResponse response = executeHttpRequest(httpPost);
if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpPost.getURI().toString());
switch (response.getStatusLine().getStatusCode()) {
case 200:
try {
return EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
throw new FoursquareParseException(e.getMessage());
}
case 401:
response.getEntity().consumeContent();
throw new FoursquareCredentialsException(response.getStatusLine().toString());
case 404:
response.getEntity().consumeContent();
throw new FoursquareException(response.getStatusLine().toString());
default:
response.getEntity().consumeContent();
throw new FoursquareException(response.getStatusLine().toString());
}
}
/**
* execute() an httpRequest catching exceptions and returning null instead.
*
* @param httpRequest
* @return
* @throws IOException
*/
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: "
+ httpRequest.getURI().toString());
try {
mHttpClient.getConnectionManager().closeExpiredConnections();
return mHttpClient.execute(httpRequest);
} catch (IOException e) {
httpRequest.abort();
throw e;
}
}
public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) {
if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url);
String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8);
HttpGet httpGet = new HttpGet(url + "?" + query);
httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI());
return httpGet;
}
public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) {
if (DEBUG) LOG.log(Level.FINE, "creating HttpPost for: " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
try {
httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(nameValuePairs), HTTP.UTF_8));
} catch (UnsupportedEncodingException e1) {
throw new IllegalArgumentException("Unable to encode http parameters.");
}
if (DEBUG) LOG.log(Level.FINE, "Created: " + httpPost);
return httpPost;
}
public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary)
throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(TIMEOUT * 1000);
conn.setRequestMethod("POST");
conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
return conn;
}
private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i = 0; i < nameValuePairs.length; i++) {
NameValuePair param = nameValuePairs[i];
if (param.getValue() != null) {
if (DEBUG) LOG.log(Level.FINE, "Param: " + param);
params.add(param);
}
}
return params;
}
/**
* Create a thread-safe client. This client does not do redirecting, to allow us to capture
* correct "error" codes.
*
* @return HttpClient
*/
public static final DefaultHttpClient createHttpClient() {
// Sets up the http part of the service.
final SchemeRegistry supportedSchemes = new SchemeRegistry();
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
final SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// Set some client http client parameter defaults.
final HttpParams httpParams = createHttpParams();
HttpClientParams.setRedirecting(httpParams, false);
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams,
supportedSchemes);
return new DefaultHttpClient(ccm, httpParams);
}
/**
* Create the default HTTP protocol parameters.
*/
private static final HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
return params;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import com.joelapenna.foursquare.util.ParcelUtils;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @date March 6, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Category implements FoursquareType, Parcelable {
/** The category's id. */
private String mId;
/** Full category path name, like Nightlife:Bars. */
private String mFullPathName;
/** Simple name of the category. */
private String mNodeName;
/** Url of the icon associated with this category. */
private String mIconUrl;
/** Categories can be nested within one another too. */
private Group<Category> mChildCategories;
public Category() {
mChildCategories = new Group<Category>();
}
private Category(Parcel in) {
mChildCategories = new Group<Category>();
mId = ParcelUtils.readStringFromParcel(in);
mFullPathName = ParcelUtils.readStringFromParcel(in);
mNodeName = ParcelUtils.readStringFromParcel(in);
mIconUrl = ParcelUtils.readStringFromParcel(in);
int numCategories = in.readInt();
for (int i = 0; i < numCategories; i++) {
Category category = in.readParcelable(Category.class.getClassLoader());
mChildCategories.add(category);
}
}
public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() {
public Category createFromParcel(Parcel in) {
return new Category(in);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
public String getId() {
return mId;
}
public void setId(String id) {
mId = id;
}
public String getFullPathName() {
return mFullPathName;
}
public void setFullPathName(String fullPathName) {
mFullPathName = fullPathName;
}
public String getNodeName() {
return mNodeName;
}
public void setNodeName(String nodeName) {
mNodeName = nodeName;
}
public String getIconUrl() {
return mIconUrl;
}
public void setIconUrl(String iconUrl) {
mIconUrl = iconUrl;
}
public Group<Category> getChildCategories() {
return mChildCategories;
}
public void setChildCategories(Group<Category> categories) {
mChildCategories = categories;
}
@Override
public void writeToParcel(Parcel out, int flags) {
ParcelUtils.writeStringToParcel(out, mId);
ParcelUtils.writeStringToParcel(out, mFullPathName);
ParcelUtils.writeStringToParcel(out, mNodeName);
ParcelUtils.writeStringToParcel(out, mIconUrl);
out.writeInt(mChildCategories.size());
for (Category it : mChildCategories) {
out.writeParcelable(it, flags);
}
}
@Override
public int describeContents() {
return 0;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
/**
* @date 2010-05-05
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Emails extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface FoursquareType {
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Group<T extends FoursquareType> extends ArrayList<T> implements FoursquareType {
private static final long serialVersionUID = 1L;
private String mType;
public Group() {
super();
}
public Group(Collection<T> collection) {
super(collection);
}
public void setType(String type) {
mType = type;
}
public String getType() {
return mType;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
/**
* @date 2010-05-05
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class FriendInvitesResult implements FoursquareType {
/**
* Users that are in our contact book by email or phone, are already on foursquare,
* but are not our friends.
*/
private Group<User> mContactsOnFoursquare;
/**
* Users not on foursquare, but in our contact book by email or phone. These are
* users we have not already sent an email invite to.
*/
private Emails mContactEmailsNotOnFoursquare;
/**
* A list of email addresses we've already sent email invites to.
*/
private Emails mContactEmailsNotOnFoursquareAlreadyInvited;
public FriendInvitesResult() {
mContactsOnFoursquare = new Group<User>();
mContactEmailsNotOnFoursquare = new Emails();
mContactEmailsNotOnFoursquareAlreadyInvited = new Emails();
}
public Group<User> getContactsOnFoursquare() {
return mContactsOnFoursquare;
}
public void setContactsOnFoursquare(Group<User> contactsOnFoursquare) {
mContactsOnFoursquare = contactsOnFoursquare;
}
public Emails getContactEmailsNotOnFoursquare() {
return mContactEmailsNotOnFoursquare;
}
public void setContactEmailsOnNotOnFoursquare(Emails emails) {
mContactEmailsNotOnFoursquare = emails;
}
public Emails getContactEmailsNotOnFoursquareAlreadyInvited() {
return mContactEmailsNotOnFoursquareAlreadyInvited;
}
public void setContactEmailsOnNotOnFoursquareAlreadyInvited(Emails emails) {
mContactEmailsNotOnFoursquareAlreadyInvited = emails;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
/**
* @date April 14, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Types extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
/**
* @date April 28, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Response implements FoursquareType {
private String mValue;
public Response() {
}
public String getValue() {
return mValue;
}
public void setValue(String value) {
mValue = value;
}
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Tags extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
public Tags() {
super();
}
public Tags(List<String> values) {
super();
addAll(values);
}
} | Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import com.joelapenna.foursquare.util.ParcelUtils;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Todo implements FoursquareType, Parcelable {
private String mCreated;
private String mId;
private Tip mTip;
public Todo() {
}
private Todo(Parcel in) {
mCreated = ParcelUtils.readStringFromParcel(in);
mId = ParcelUtils.readStringFromParcel(in);
if (in.readInt() == 1) {
mTip = in.readParcelable(Tip.class.getClassLoader());
}
}
public static final Parcelable.Creator<Todo> CREATOR = new Parcelable.Creator<Todo>() {
public Todo createFromParcel(Parcel in) {
return new Todo(in);
}
@Override
public Todo[] newArray(int size) {
return new Todo[size];
}
};
public String getCreated() {
return mCreated;
}
public void setCreated(String created) {
mCreated = created;
}
public String getId() {
return mId;
}
public void setId(String id) {
mId = id;
}
public Tip getTip() {
return mTip;
}
public void setTip(Tip tip) {
mTip = tip;
}
@Override
public void writeToParcel(Parcel out, int flags) {
ParcelUtils.writeStringToParcel(out, mCreated);
ParcelUtils.writeStringToParcel(out, mId);
if (mTip != null) {
out.writeInt(1);
out.writeParcelable(mTip, flags);
} else {
out.writeInt(0);
}
}
@Override
public int describeContents() {
return 0;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.util;
import android.os.Parcel;
/**
* @date March 25, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ParcelUtils {
public static void writeStringToParcel(Parcel out, String str) {
if (str != null) {
out.writeInt(1);
out.writeString(str);
} else {
out.writeInt(0);
}
}
public static String readStringFromParcel(Parcel in) {
int flag = in.readInt();
if (flag == 1) {
return in.readString();
} else {
return null;
}
}
} | Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.util;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class MayorUtils {
public static final String TYPE_NOCHANGE = "nochange";
public static final String TYPE_NEW = "new";
public static final String TYPE_STOLEN = "stolen";
}
| Java |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.util;
import com.joelapenna.foursquare.types.Venue;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueUtils {
public static final boolean isValid(Venue venue) {
return !(venue == null || venue.getId() == null || venue.getId().length() == 0);
}
public static final boolean hasValidLocation(Venue venue) {
boolean valid = false;
if (venue != null) {
String geoLat = venue.getGeolat();
String geoLong = venue.getGeolong();
if (!(geoLat == null || geoLat.length() == 0 || geoLong == null || geoLong.length() == 0)) {
if (geoLat != "0" || geoLong != "0") {
valid = true;
}
}
}
return valid;
}
}
| Java |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.util;
/**
* This is not ideal.
*
* @date July 1, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class IconUtils {
private static IconUtils mInstance;
private boolean mRequestHighDensityIcons;
private IconUtils() {
mRequestHighDensityIcons = false;
}
public static IconUtils get() {
if (mInstance == null) {
mInstance = new IconUtils();
}
return mInstance;
}
public boolean getRequestHighDensityIcons() {
return mRequestHighDensityIcons;
}
public void setRequestHighDensityIcons(boolean requestHighDensityIcons) {
mRequestHighDensityIcons = requestHighDensityIcons;
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.