code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package org.anddev.andengine.util.pool;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
/**
* @author Valentin Milea
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
*
* @since 23:02:58 - 21.08.2010
* @param <T>
*/
public abstract class PoolUpdateHandler<T extends PoolItem> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final Pool<T> mPool;
private final ArrayList<T> mScheduledPoolItems = new ArrayList<T>();
// ===========================================================
// Constructors
// ===========================================================
public PoolUpdateHandler() {
this.mPool = new Pool<T>() {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize) {
this.mPool = new Pool<T>(pInitialPoolSize) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
public PoolUpdateHandler(final int pInitialPoolSize, final int pGrowth) {
this.mPool = new Pool<T>(pInitialPoolSize, pGrowth) {
@Override
protected T onAllocatePoolItem() {
return PoolUpdateHandler.this.onAllocatePoolItem();
}
};
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract T onAllocatePoolItem();
protected abstract void onHandlePoolItem(final T pPoolItem);
@Override
public void onUpdate(final float pSecondsElapsed) {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
if(count > 0) {
final Pool<T> pool = this.mPool;
T item;
for(int i = 0; i < count; i++) {
item = scheduledPoolItems.get(i);
this.onHandlePoolItem(item);
pool.recyclePoolItem(item);
}
scheduledPoolItems.clear();
}
}
}
@Override
public void reset() {
final ArrayList<T> scheduledPoolItems = this.mScheduledPoolItems;
synchronized (scheduledPoolItems) {
final int count = scheduledPoolItems.size();
final Pool<T> pool = this.mPool;
for(int i = count - 1; i >= 0; i--) {
pool.recyclePoolItem(scheduledPoolItems.get(i));
}
scheduledPoolItems.clear();
}
}
// ===========================================================
// Methods
// ===========================================================
public T obtainPoolItem() {
return this.mPool.obtainPoolItem();
}
public void postPoolItem(final T pPoolItem) {
synchronized (this.mScheduledPoolItems) {
if(pPoolItem == null) {
throw new IllegalArgumentException("PoolItem already recycled!");
} else if(!this.mPool.ownsPoolItem(pPoolItem)) {
throw new IllegalArgumentException("PoolItem from another pool!");
}
this.mScheduledPoolItems.add(pPoolItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:35:42 - 01.05.2011
*/
public class ArrayUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static <T> T random(final T[] pArray) {
return pArray[MathUtils.random(0, pArray.length - 1)];
}
public static void reverse(final byte[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
byte tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final short[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
short tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final int[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
int tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final long[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
long tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final float[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
float tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final double[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
double tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static void reverse(final Object[] pArray) {
if (pArray == null) {
return;
}
int i = 0;
int j = pArray.length - 1;
Object tmp;
while (j > i) {
tmp = pArray[j];
pArray[j] = pArray[i];
pArray[i] = tmp;
j--;
i++;
}
}
public static boolean equals(final byte[] pArrayA, final int pOffsetA, final byte[] pArrayB, final int pOffsetB, final int pLength) {
final int lastIndexA = pOffsetA + pLength;
if(lastIndexA > pArrayA.length) {
throw new ArrayIndexOutOfBoundsException(pArrayA.length);
}
final int lastIndexB = pOffsetB + pLength;
if(lastIndexB > pArrayB.length) {
throw new ArrayIndexOutOfBoundsException(pArrayB.length);
}
for(int a = pOffsetA, b = pOffsetB; a < lastIndexA; a++, b++) {
if(pArrayA[a] != pArrayB[b]) {
return false;
}
}
return true;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import android.graphics.Color;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:13:45 - 04.08.2010
*/
public class ColorUtils {
// ===========================================================
// Constants
// ===========================================================
private static final float[] HSV_TO_COLOR = new float[3];
private static final int HSV_TO_COLOR_HUE_INDEX = 0;
private static final int HSV_TO_COLOR_SATURATION_INDEX = 1;
private static final int HSV_TO_COLOR_VALUE_INDEX = 2;
private static final int COLOR_FLOAT_TO_INT_FACTOR = 255;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pHue [0 .. 360)
* @param pSaturation [0...1]
* @param pValue [0...1]
*/
public static int HSVToColor(final float pHue, final float pSaturation, final float pValue) {
HSV_TO_COLOR[HSV_TO_COLOR_HUE_INDEX] = pHue;
HSV_TO_COLOR[HSV_TO_COLOR_SATURATION_INDEX] = pSaturation;
HSV_TO_COLOR[HSV_TO_COLOR_VALUE_INDEX] = pValue;
return Color.HSVToColor(HSV_TO_COLOR);
}
public static int RGBToColor(final float pRed, final float pGreen, final float pBlue) {
return Color.rgb((int)(pRed * COLOR_FLOAT_TO_INT_FACTOR), (int)(pGreen * COLOR_FLOAT_TO_INT_FACTOR), (int)(pBlue * COLOR_FLOAT_TO_INT_FACTOR));
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import java.util.Arrays;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:21:22 - 03.09.2010
* @param <T>
*/
public class ParallelModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
private final float mDuration;
private final IModifier<T>[] mModifiers;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public ParallelModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifiers);
}
public ParallelModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
super(pModifierListener);
if(pModifiers.length == 0) {
throw new IllegalArgumentException("pModifiers must not be empty!");
}
Arrays.sort(pModifiers, MODIFIER_COMPARATOR_DURATION_DESCENDING);
this.mModifiers = pModifiers;
final IModifier<T> modifierWithLongestDuration = pModifiers[0];
this.mDuration = modifierWithLongestDuration.getDuration();
modifierWithLongestDuration.addModifierListener(this);
}
@SuppressWarnings("unchecked")
protected ParallelModifier(final ParallelModifier<T> pParallelModifier) throws DeepCopyNotSupportedException {
final IModifier<T>[] otherModifiers = pParallelModifier.mModifiers;
this.mModifiers = new IModifier[otherModifiers.length];
final IModifier<T>[] modifiers = this.mModifiers;
for(int i = modifiers.length - 1; i >= 0; i--) {
modifiers[i] = otherModifiers[i].deepCopy();
}
final IModifier<T> modifierWithLongestDuration = modifiers[0];
this.mDuration = modifierWithLongestDuration.getDuration();
modifierWithLongestDuration.addModifierListener(this);
}
@Override
public ParallelModifier<T> deepCopy() throws DeepCopyNotSupportedException{
return new ParallelModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
final IModifier<T>[] shapeModifiers = this.mModifiers;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
float secondsElapsedUsed = 0;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
secondsElapsedUsed = Math.max(secondsElapsedUsed, shapeModifiers[i].onUpdate(pSecondsElapsed, pItem));
}
secondsElapsedRemaining -= secondsElapsedUsed;
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mFinished = false;
this.mSecondsElapsed = 0;
final IModifier<T>[] shapeModifiers = this.mModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
this.onModifierStarted(pItem);
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartInOut() {
}
public static EaseQuartInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseQuartIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuartOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialInOut() {
}
public static EaseExponentialInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseExponentialIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseExponentialOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:50:40 - 26.07.2010
*/
public class EaseLinear implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseLinear INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseLinear() {
}
public static EaseLinear getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseLinear();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return pSecondsElapsed / pDuration;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBackInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackInOut() {
}
public static EaseBackInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBackInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseBackIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseBackOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartIn() {
}
public static EaseQuartIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuartIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularIn() {
}
public static EaseCircularIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCircularIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -(FloatMath.sqrt(1 - pPercentage * pPercentage) - 1.0f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialIn() {
}
public static EaseExponentialIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseExponentialIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return (float) ((pPercentage == 0) ? 0 : Math.pow(2, 10 * (pPercentage - 1)) - 0.001f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicOut() {
}
public static EaseCubicOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCubicOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicIn() {
}
public static EaseCubicIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCubicIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 17:13:17 - 26.07.2010
*/
public interface IEaseFunction {
// ===========================================================
// Final Fields
// ===========================================================
public static final IEaseFunction DEFAULT = EaseLinear.getInstance();
// ===========================================================
// Methods
// ===========================================================
public float getPercentage(final float pSecondsElapsed, final float pDuration);
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongIn() {
}
public static EaseStrongIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseStrongIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadIn() {
}
public static EaseQuadIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuadIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticIn implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticIn() {
}
public static EaseElasticIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseElasticIn.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentage) {
if(pSecondsElapsed == 0) {
return 0;
}
if(pSecondsElapsed == pDuration) {
return 1;
}
final float p = pDuration * 0.3f;
final float s = p / 4;
final float t = pPercentage - 1;
return -(float)Math.pow(2, 10 * t) * FloatMath.sin((t * pDuration - s) * PI_TWICE / p);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintOut() {
}
public static EaseQuintOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuintOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceInOut() {
}
public static EaseBounceInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseBounceIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseBounceOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseExponentialOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseExponentialOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseExponentialOut() {
}
public static EaseExponentialOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseExponentialOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseExponentialOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return (pPercentage == 1) ? 1 : (-(float)Math.pow(2, -10 * pPercentage) + 1);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadOut() {
}
public static EaseQuadOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuadOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -pPercentage * (pPercentage - 2);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import static org.anddev.andengine.util.constants.MathConstants.PI;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineInOut() {
}
public static EaseSineInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
return -0.5f * (FloatMath.cos(percentage * PI) - 1);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintInOut() {
}
public static EaseQuintInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseQuintIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuintOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticInOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticInOut() {
}
public static EaseElasticInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseElasticIn.getValue(2 * pSecondsElapsed, pDuration, 2 * percentage);
} else {
return 0.5f + 0.5f * EaseElasticOut.getValue(pSecondsElapsed * 2 - pDuration, pDuration, percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseElasticOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseElasticOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseElasticOut() {
}
public static EaseElasticOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseElasticOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseElasticOut.getValue(pSecondsElapsed, pDuration, pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pSecondsElapsed, final float pDuration, final float pPercentageDone) {
if(pSecondsElapsed == 0) {
return 0;
}
if(pSecondsElapsed == pDuration) {
return 1;
}
final float p = pDuration * 0.3f;
final float s = p / 4;
return 1 + (float)Math.pow(2, -10 * pPercentageDone) * FloatMath.sin((pPercentageDone * pDuration - s) * PI_TWICE / p);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularOut() {
}
public static EaseCircularOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseCircularOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return FloatMath.sqrt(1 - t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCircularInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCircularInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCircularInOut() {
}
public static EaseCircularInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCircularInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseCircularIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseCircularOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuintIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuintIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuintIn() {
}
public static EaseQuintIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuintIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuintIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * pPercentage * pPercentage * pPercentage;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongInOut() {
}
public static EaseStrongInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseStrongIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseStrongOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuartOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuartOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuartOut() {
}
public static EaseQuartOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuartOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseQuartOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 - (t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseQuadInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseQuadInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseQuadInOut() {
}
public static EaseQuadInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseQuadInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseQuadIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseQuadOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
private static final float OVERSHOOT_CONSTANT = 1.70158f;
// ===========================================================
// Fields
// ===========================================================
private static EaseBackIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackIn() {
}
public static EaseBackIn getInstance() {
if(null == INSTANCE) {
INSTANCE = new EaseBackIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBackIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return pPercentage * pPercentage * ((OVERSHOOT_CONSTANT + 1) * pPercentage - OVERSHOOT_CONSTANT);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseCubicInOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseCubicInOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseCubicInOut() {
}
public static EaseCubicInOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseCubicInOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
final float percentage = pSecondsElapsed / pDuration;
if(percentage < 0.5f) {
return 0.5f * EaseCubicIn.getValue(2 * percentage);
} else {
return 0.5f + 0.5f * EaseCubicOut.getValue(percentage * 2 - 1);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceIn implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceIn() {
}
public static EaseBounceIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBounceIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
// TODO Inline?
return 1 - EaseBounceOut.getValue(1 - pPercentage);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineOut implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineOut() {
}
public static EaseSineOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseSineOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return FloatMath.sin(pPercentage * PI_HALF);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBackOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBackOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBackOut() {
}
public static EaseBackOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBackOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBackOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + t * t * ((1.70158f + 1) * t + 1.70158f);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseStrongOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseStrongOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseStrongOut() {
}
public static EaseStrongOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseStrongOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseStrongOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
final float t = pPercentage - 1;
return 1 + (t * t * t * t * t);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseBounceOut implements IEaseFunction {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseBounceOut INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseBounceOut() {
}
public static EaseBounceOut getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseBounceOut();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseBounceOut.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
if(pPercentage < (1f / 2.75f)) {
return 7.5625f * pPercentage * pPercentage;
} else if(pPercentage < (2f / 2.75f)) {
final float t = pPercentage - (1.5f / 2.75f);
return 7.5625f * t * t + 0.75f;
} else if(pPercentage < (2.5f / 2.75f)) {
final float t = pPercentage - (2.25f / 2.75f);
return 7.5625f * t * t + 0.9375f;
} else {
final float t = pPercentage - (2.625f / 2.75f);
return 7.5625f * t * t + 0.984375f;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier.ease;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Gil
* @author Nicolas Gramlich
* @since 16:52:11 - 26.07.2010
*/
public class EaseSineIn implements IEaseFunction, MathConstants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static EaseSineIn INSTANCE;
// ===========================================================
// Constructors
// ===========================================================
private EaseSineIn() {
}
public static EaseSineIn getInstance() {
if(INSTANCE == null) {
INSTANCE = new EaseSineIn();
}
return INSTANCE;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getPercentage(final float pSecondsElapsed, final float pDuration) {
return EaseSineIn.getValue(pSecondsElapsed / pDuration);
}
// ===========================================================
// Methods
// ===========================================================
public static float getValue(final float pPercentage) {
return -FloatMath.cos(pPercentage * PI_HALF) + 1;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:52:31 - 03.09.2010
* @param <T>
*/
public abstract class BaseTripleValueSpanModifier<T> extends BaseDoubleValueSpanModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValueC;
private final float mValueSpanC;
// ===========================================================
// Constructors
// ===========================================================
public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IEaseFunction pEaseFunction) {
this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pFromValueC, pToValueC, null, pEaseFunction);
}
public BaseTripleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final float pFromValueC, final float pToValueC, final IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, pEaseFunction);
this.mFromValueC = pFromValueC;
this.mValueSpanC = pToValueC - pFromValueC;
}
protected BaseTripleValueSpanModifier(final BaseTripleValueSpanModifier<T> pBaseTripleValueSpanModifier) {
super(pBaseTripleValueSpanModifier);
this.mFromValueC = pBaseTripleValueSpanModifier.mFromValueC;
this.mValueSpanC = pBaseTripleValueSpanModifier.mValueSpanC;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB, final float pValueC);
protected abstract void onSetValues(final T pItem, final float pPerctentageDone, final float pValueA, final float pValueB, final float pValueC);
@Override
protected void onSetInitialValues(final T pItem, final float pValueA, final float pValueB) {
this.onSetInitialValues(pItem, pValueA, pValueB, this.mFromValueC);
}
@Override
protected void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB) {
this.onSetValues(pItem, pPercentageDone, pValueA, pValueB, this.mFromValueC + pPercentageDone * this.mValueSpanC);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:18:37 - 03.09.2010
* @param <T>
*/
public class LoopModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
public static final int LOOP_CONTINUOUS = -1;
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
private final float mDuration;
private final IModifier<T> mModifier;
private ILoopModifierListener<T> mLoopModifierListener;
private final int mLoopCount;
private int mLoop;
private boolean mModifierStartedCalled;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public LoopModifier(final IModifier<T> pModifier) {
this(pModifier, LOOP_CONTINUOUS);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount) {
this(pModifier, pLoopCount, null, (IModifierListener<T>)null);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final IModifierListener<T> pModifierListener) {
this(pModifier, pLoopCount, null, pModifierListener);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener) {
this(pModifier, pLoopCount, pLoopModifierListener, (IModifierListener<T>)null);
}
public LoopModifier(final IModifier<T> pModifier, final int pLoopCount, final ILoopModifierListener<T> pLoopModifierListener, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mModifier = pModifier;
this.mLoopCount = pLoopCount;
this.mLoopModifierListener = pLoopModifierListener;
this.mLoop = 0;
this.mDuration = pLoopCount == LOOP_CONTINUOUS ? Float.POSITIVE_INFINITY : pModifier.getDuration() * pLoopCount; // TODO Check if POSITIVE_INFINITY works correct with i.e. SequenceModifier
this.mModifier.addModifierListener(this);
}
protected LoopModifier(final LoopModifier<T> pLoopModifier) throws DeepCopyNotSupportedException {
this(pLoopModifier.mModifier.deepCopy(), pLoopModifier.mLoopCount);
}
@Override
public LoopModifier<T> deepCopy() throws DeepCopyNotSupportedException {
return new LoopModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ILoopModifierListener<T> getLoopModifierListener() {
return this.mLoopModifierListener;
}
public void setLoopModifierListener(final ILoopModifierListener<T> pLoopModifierListener) {
this.mLoopModifierListener = pLoopModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
secondsElapsedRemaining -= this.mModifier.onUpdate(secondsElapsedRemaining, pItem);
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mLoop = 0;
this.mSecondsElapsed = 0;
this.mModifierStartedCalled = false;
this.mModifier.reset();
}
// ===========================================================
// Methods
// ===========================================================
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
if(!this.mModifierStartedCalled) {
this.mModifierStartedCalled = true;
this.onModifierStarted(pItem);
}
if(this.mLoopModifierListener != null) {
this.mLoopModifierListener.onLoopStarted(this, this.mLoop, this.mLoopCount);
}
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
if(this.mLoopModifierListener != null) {
this.mLoopModifierListener.onLoopFinished(this, this.mLoop, this.mLoopCount);
}
if(this.mLoopCount == LOOP_CONTINUOUS) {
this.mSecondsElapsed = 0;
this.mModifier.reset();
} else {
this.mLoop++;
if(this.mLoop >= this.mLoopCount) {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
} else {
this.mSecondsElapsed = 0;
this.mModifier.reset();
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ILoopModifierListener<T> {
public void onLoopStarted(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
public void onLoopFinished(final LoopModifier<T> pLoopModifier, final int pLoop, final int pLoopCount);
}
}
| Java |
package org.anddev.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:49:51 - 03.09.2010
* @param <T>
*/
public abstract class BaseSingleValueChangeModifier<T> extends BaseDurationModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mValueChangePerSecond;
// ===========================================================
// Constructors
// ===========================================================
public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange) {
this(pDuration, pValueChange, null);
}
public BaseSingleValueChangeModifier(final float pDuration, final float pValueChange, final IModifierListener<T> pModifierListener) {
super(pDuration, pModifierListener);
this.mValueChangePerSecond = pValueChange / pDuration;
}
protected BaseSingleValueChangeModifier(final BaseSingleValueChangeModifier<T> pBaseSingleValueChangeModifier) {
super(pBaseSingleValueChangeModifier);
this.mValueChangePerSecond = pBaseSingleValueChangeModifier.mValueChangePerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValue);
@Override
protected void onManagedInitialize(final T pItem) {
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) {
this.onChangeValue(pSecondsElapsed, pItem, this.mValueChangePerSecond * pSecondsElapsed);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:29:22 - 19.03.2010
*/
public abstract class BaseSingleValueSpanModifier<T> extends BaseDurationModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValue;
private final float mValueSpan;
protected final IEaseFunction mEaseFunction;
// ===========================================================
// Constructors
// ===========================================================
public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue) {
this(pDuration, pFromValue, pToValue, null, IEaseFunction.DEFAULT);
}
public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IEaseFunction pEaseFunction) {
this(pDuration, pFromValue, pToValue, null, pEaseFunction);
}
public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener<T> pModifierListener) {
this(pDuration, pFromValue, pToValue, pModifierListener, IEaseFunction.DEFAULT);
}
public BaseSingleValueSpanModifier(final float pDuration, final float pFromValue, final float pToValue, final IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pModifierListener);
this.mFromValue = pFromValue;
this.mValueSpan = pToValue - pFromValue;
this.mEaseFunction = pEaseFunction;
}
protected BaseSingleValueSpanModifier(final BaseSingleValueSpanModifier<T> pBaseSingleValueSpanModifier) {
super(pBaseSingleValueSpanModifier);
this.mFromValue = pBaseSingleValueSpanModifier.mFromValue;
this.mValueSpan = pBaseSingleValueSpanModifier.mValueSpan;
this.mEaseFunction = pBaseSingleValueSpanModifier.mEaseFunction;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onSetInitialValue(final T pItem, final float pValue);
protected abstract void onSetValue(final T pItem, final float pPercentageDone, final float pValue);
@Override
protected void onManagedInitialize(final T pItem) {
this.onSetInitialValue(pItem, this.mFromValue);
}
@Override
protected void onManagedUpdate(final float pSecondsElapsed, final T pItem) {
final float percentageDone = this.mEaseFunction.getPercentage(this.getSecondsElapsed(), this.mDuration);
this.onSetValue(pItem, percentageDone, this.mFromValue + percentageDone * this.mValueSpan);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:47:23 - 03.09.2010
* @param <T>
*/
public abstract class BaseModifier<T> implements IModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected boolean mFinished;
private boolean mRemoveWhenFinished = true;
private final SmartList<IModifierListener<T>> mModifierListeners = new SmartList<IModifierListener<T>>(2);
// ===========================================================
// Constructors
// ===========================================================
public BaseModifier() {
}
public BaseModifier(final IModifierListener<T> pModifierListener) {
this.addModifierListener(pModifierListener);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public boolean isFinished() {
return this.mFinished;
}
@Override
public final boolean isRemoveWhenFinished() {
return this.mRemoveWhenFinished;
}
@Override
public final void setRemoveWhenFinished(final boolean pRemoveWhenFinished) {
this.mRemoveWhenFinished = pRemoveWhenFinished;
}
@Override
public void addModifierListener(final IModifierListener<T> pModifierListener) {
if(pModifierListener != null) {
this.mModifierListeners.add(pModifierListener);
}
}
@Override
public boolean removeModifierListener(final IModifierListener<T> pModifierListener) {
if(pModifierListener == null) {
return false;
} else {
return this.mModifierListeners.remove(pModifierListener);
}
}
@Override
public abstract IModifier<T> deepCopy() throws DeepCopyNotSupportedException;
// ===========================================================
// Methods
// ===========================================================
protected void onModifierStarted(final T pItem) {
final SmartList<IModifierListener<T>> modifierListeners = this.mModifierListeners;
final int modifierListenerCount = modifierListeners.size();
for(int i = modifierListenerCount - 1; i >= 0; i--) {
modifierListeners.get(i).onModifierStarted(this, pItem);
}
}
protected void onModifierFinished(final T pItem) {
final SmartList<IModifierListener<T>> modifierListeners = this.mModifierListeners;
final int modifierListenerCount = modifierListeners.size();
for(int i = modifierListenerCount - 1; i >= 0; i--) {
modifierListeners.get(i).onModifierFinished(this, pItem);
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.IModifier.IModifierListener;
import org.anddev.andengine.util.modifier.util.ModifierUtils;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 19:39:25 - 19.03.2010
*/
public class SequenceModifier<T> extends BaseModifier<T> implements IModifierListener<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private ISubSequenceModifierListener<T> mSubSequenceModifierListener;
private final IModifier<T>[] mSubSequenceModifiers;
private int mCurrentSubSequenceModifierIndex;
private float mSecondsElapsed;
private final float mDuration;
private boolean mFinishedCached;
// ===========================================================
// Constructors
// ===========================================================
public SequenceModifier(final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, null, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(pSubSequenceModifierListener, null, pModifiers);
}
public SequenceModifier(final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
this(null, pModifierListener, pModifiers);
}
public SequenceModifier(final ISubSequenceModifierListener<T> pSubSequenceModifierListener, final IModifierListener<T> pModifierListener, final IModifier<T> ... pModifiers) throws IllegalArgumentException {
super(pModifierListener);
if (pModifiers.length == 0) {
throw new IllegalArgumentException("pModifiers must not be empty!");
}
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
this.mSubSequenceModifiers = pModifiers;
this.mDuration = ModifierUtils.getSequenceDurationOfModifier(pModifiers);
pModifiers[0].addModifierListener(this);
}
@SuppressWarnings("unchecked")
protected SequenceModifier(final SequenceModifier<T> pSequenceModifier) throws DeepCopyNotSupportedException {
this.mDuration = pSequenceModifier.mDuration;
final IModifier<T>[] otherModifiers = pSequenceModifier.mSubSequenceModifiers;
this.mSubSequenceModifiers = new IModifier[otherModifiers.length];
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i] = otherModifiers[i].deepCopy();
}
shapeModifiers[0].addModifierListener(this);
}
@Override
public SequenceModifier<T> deepCopy() throws DeepCopyNotSupportedException{
return new SequenceModifier<T>(this);
}
// ===========================================================
// Getter & Setter
// ===========================================================
public ISubSequenceModifierListener<T> getSubSequenceModifierListener() {
return this.mSubSequenceModifierListener;
}
public void setSubSequenceModifierListener(final ISubSequenceModifierListener<T> pSubSequenceModifierListener) {
this.mSubSequenceModifierListener = pSubSequenceModifierListener;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
@Override
public float getDuration() {
return this.mDuration;
}
@Override
public float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
float secondsElapsedRemaining = pSecondsElapsed;
this.mFinishedCached = false;
while(secondsElapsedRemaining > 0 && !this.mFinishedCached) {
secondsElapsedRemaining -= this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].onUpdate(secondsElapsedRemaining, pItem);
}
this.mFinishedCached = false;
final float secondsElapsedUsed = pSecondsElapsed - secondsElapsedRemaining;
this.mSecondsElapsed += secondsElapsedUsed;
return secondsElapsedUsed;
}
}
@Override
public void reset() {
if(this.isFinished()) {
this.mSubSequenceModifiers[this.mSubSequenceModifiers.length - 1].removeModifierListener(this);
} else {
this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex].removeModifierListener(this);
}
this.mCurrentSubSequenceModifierIndex = 0;
this.mFinished = false;
this.mSecondsElapsed = 0;
this.mSubSequenceModifiers[0].addModifierListener(this);
final IModifier<T>[] shapeModifiers = this.mSubSequenceModifiers;
for(int i = shapeModifiers.length - 1; i >= 0; i--) {
shapeModifiers[i].reset();
}
}
@Override
public void onModifierStarted(final IModifier<T> pModifier, final T pItem) {
if(this.mCurrentSubSequenceModifierIndex == 0) {
this.onModifierStarted(pItem);
}
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceStarted(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
}
@Override
public void onModifierFinished(final IModifier<T> pModifier, final T pItem) {
if(this.mSubSequenceModifierListener != null) {
this.mSubSequenceModifierListener.onSubSequenceFinished(pModifier, pItem, this.mCurrentSubSequenceModifierIndex);
}
pModifier.removeModifierListener(this);
this.mCurrentSubSequenceModifierIndex++;
if(this.mCurrentSubSequenceModifierIndex < this.mSubSequenceModifiers.length) {
final IModifier<T> nextSubSequenceModifier = this.mSubSequenceModifiers[this.mCurrentSubSequenceModifierIndex];
nextSubSequenceModifier.addModifierListener(this);
} else {
this.mFinished = true;
this.mFinishedCached = true;
this.onModifierFinished(pItem);
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public interface ISubSequenceModifierListener<T> {
public void onSubSequenceStarted(final IModifier<T> pModifier, final T pItem, final int pIndex);
public void onSubSequenceFinished(final IModifier<T> pModifier, final T pItem, final int pIndex);
}
}
| Java |
package org.anddev.andengine.util.modifier;
import org.anddev.andengine.util.modifier.ease.IEaseFunction;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:51:46 - 03.09.2010
* @param <T>
*/
public abstract class BaseDoubleValueSpanModifier<T> extends BaseSingleValueSpanModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private final float mFromValueB;
private final float mValueSpanB;
// ===========================================================
// Constructors
// ===========================================================
public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB) {
this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, IEaseFunction.DEFAULT);
}
public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IEaseFunction pEaseFunction) {
this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, null, pEaseFunction);
}
public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener<T> pModifierListener) {
this(pDuration, pFromValueA, pToValueA, pFromValueB, pToValueB, pModifierListener, IEaseFunction.DEFAULT);
}
public BaseDoubleValueSpanModifier(final float pDuration, final float pFromValueA, final float pToValueA, final float pFromValueB, final float pToValueB, final IModifierListener<T> pModifierListener, final IEaseFunction pEaseFunction) {
super(pDuration, pFromValueA, pToValueA, pModifierListener, pEaseFunction);
this.mFromValueB = pFromValueB;
this.mValueSpanB = pToValueB - pFromValueB;
}
protected BaseDoubleValueSpanModifier(final BaseDoubleValueSpanModifier<T> pBaseDoubleValueSpanModifier) {
super(pBaseDoubleValueSpanModifier);
this.mFromValueB = pBaseDoubleValueSpanModifier.mFromValueB;
this.mValueSpanB = pBaseDoubleValueSpanModifier.mValueSpanB;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
protected abstract void onSetInitialValues(final T pItem, final float pValueA, final float pValueB);
protected abstract void onSetValues(final T pItem, final float pPercentageDone, final float pValueA, final float pValueB);
@Override
protected void onSetInitialValue(final T pItem, final float pValueA) {
this.onSetInitialValues(pItem, pValueA, this.mFromValueB);
}
@Override
protected void onSetValue(final T pItem, final float pPercentageDone, final float pValueA) {
this.onSetValues(pItem, pPercentageDone, pValueA, this.mFromValueB + pPercentageDone * this.mValueSpanB);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:48:13 - 03.09.2010
* @param <T>
*/
public abstract class BaseDurationModifier<T> extends BaseModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mSecondsElapsed;
protected final float mDuration;
// ===========================================================
// Constructors
// ===========================================================
public BaseDurationModifier(final float pDuration) {
this.mDuration = pDuration;
}
public BaseDurationModifier(final float pDuration, final IModifierListener<T> pModifierListener) {
super(pModifierListener);
this.mDuration = pDuration;
}
protected BaseDurationModifier(final BaseDurationModifier<T> pBaseModifier) {
this(pBaseModifier.mDuration);
}
// ===========================================================
// Getter & Setter
// ===========================================================
@Override
public float getSecondsElapsed() {
return this.mSecondsElapsed;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public float getDuration() {
return this.mDuration;
}
protected abstract void onManagedUpdate(final float pSecondsElapsed, final T pItem);
protected abstract void onManagedInitialize(final T pItem);
@Override
public final float onUpdate(final float pSecondsElapsed, final T pItem) {
if(this.mFinished){
return 0;
} else {
if(this.mSecondsElapsed == 0) {
this.onManagedInitialize(pItem);
this.onModifierStarted(pItem);
}
final float secondsElapsedUsed;
if(this.mSecondsElapsed + pSecondsElapsed < this.mDuration) {
secondsElapsedUsed = pSecondsElapsed;
} else {
secondsElapsedUsed = this.mDuration - this.mSecondsElapsed;
}
this.mSecondsElapsed += secondsElapsedUsed;
this.onManagedUpdate(secondsElapsedUsed, pItem);
if(this.mDuration != -1 && this.mSecondsElapsed >= this.mDuration) {
this.mSecondsElapsed = this.mDuration;
this.mFinished = true;
this.onModifierFinished(pItem);
}
return secondsElapsedUsed;
}
}
@Override
public void reset() {
this.mFinished = false;
this.mSecondsElapsed = 0;
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import java.util.ArrayList;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.util.SmartList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:34:57 - 03.09.2010
*/
public class ModifierList<T> extends SmartList<IModifier<T>> implements IUpdateHandler {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = 1610345592534873475L;
// ===========================================================
// Fields
// ===========================================================
private final T mTarget;
// ===========================================================
// Constructors
// ===========================================================
public ModifierList(final T pTarget) {
this.mTarget = pTarget;
}
public ModifierList(final T pTarget, final int pCapacity){
super(pCapacity);
this.mTarget = pTarget;
}
// ===========================================================
// Getter & Setter
// ===========================================================
public T getTarget() {
return this.mTarget;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void onUpdate(final float pSecondsElapsed) {
final ArrayList<IModifier<T>> modifiers = this;
final int modifierCount = this.size();
if(modifierCount > 0) {
for(int i = modifierCount - 1; i >= 0; i--) {
final IModifier<T> modifier = modifiers.get(i);
modifier.onUpdate(pSecondsElapsed, this.mTarget);
if(modifier.isFinished() && modifier.isRemoveWhenFinished()) {
modifiers.remove(i);
}
}
}
}
@Override
public void reset() {
final ArrayList<IModifier<T>> modifiers = this;
for(int i = modifiers.size() - 1; i >= 0; i--) {
modifiers.get(i).reset();
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
import java.util.Comparator;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:17:50 - 19.03.2010
*/
public interface IModifier<T> {
// ===========================================================
// Final Fields
// ===========================================================
public static final Comparator<IModifier<?>> MODIFIER_COMPARATOR_DURATION_DESCENDING = new Comparator<IModifier<?>>() {
@Override
public int compare(final IModifier<?> pModifierA, final IModifier<?> pModifierB) {
final float durationA = pModifierA.getDuration();
final float durationB = pModifierB.getDuration();
if (durationA < durationB) {
return 1;
} else if (durationA > durationB) {
return -1;
} else {
return 0;
}
}
};
// ===========================================================
// Methods
// ===========================================================
public void reset();
public boolean isFinished();
public boolean isRemoveWhenFinished();
public void setRemoveWhenFinished(final boolean pRemoveWhenFinished);
public IModifier<T> deepCopy() throws DeepCopyNotSupportedException;
public float getSecondsElapsed();
public float getDuration();
public float onUpdate(final float pSecondsElapsed, final T pItem);
public void addModifierListener(final IModifierListener<T> pModifierListener);
public boolean removeModifierListener(final IModifierListener<T> pModifierListener);
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface IModifierListener<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onModifierStarted(final IModifier<T> pModifier, final T pItem);
public void onModifierFinished(final IModifier<T> pModifier, final T pItem);
}
public static class DeepCopyNotSupportedException extends RuntimeException {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -5838035434002587320L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
}
| Java |
package org.anddev.andengine.util.modifier.util;
import org.anddev.andengine.util.modifier.IModifier;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 11:16:36 - 03.09.2010
*/
public class ModifierUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static float getSequenceDurationOfModifier(final IModifier<?>[] pModifiers){
float duration = Float.MIN_VALUE;
for(int i = pModifiers.length - 1; i >= 0; i--) {
duration += pModifiers[i].getDuration();
}
return duration;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util.modifier;
/**
* (c) Zynga 2011
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 14:17:30 - 10.08.2011
*/
public abstract class BaseDoubleValueChangeModifier<T> extends BaseSingleValueChangeModifier<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private float mValueChangeBPerSecond;
// ===========================================================
// Constructors
// ===========================================================
public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB) {
this(pDuration, pValueChangeA, pValueChangeB, null);
}
public BaseDoubleValueChangeModifier(final float pDuration, final float pValueChangeA, final float pValueChangeB, final IModifierListener<T> pModifierListener) {
super(pDuration, pValueChangeA, pModifierListener);
this.mValueChangeBPerSecond = pValueChangeB / pDuration;
}
protected BaseDoubleValueChangeModifier(final BaseDoubleValueChangeModifier<T> pBaseDoubleValueChangeModifier) {
super(pBaseDoubleValueChangeModifier);
this.mValueChangeBPerSecond = pBaseDoubleValueChangeModifier.mValueChangeBPerSecond;
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
protected void onChangeValue(final float pSecondsElapsed, final T pItem, final float pValueA) {
this.onChangeValues(pSecondsElapsed, pItem, pValueA, pSecondsElapsed * this.mValueChangeBPerSecond);
}
protected abstract void onChangeValues(float pSecondsElapsed, T pItem, float pValueA, float pValueB);
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import org.anddev.andengine.util.pool.GenericPool;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 23:07:53 - 23.02.2011
*/
public class TransformationPool {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static final GenericPool<Transformation> POOL = new GenericPool<Transformation>() {
@Override
protected Transformation onAllocatePoolItem() {
return new Transformation();
}
};
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public static Transformation obtain() {
return POOL.obtainPoolItem();
}
public static void recycle(final Transformation pTransformation) {
pTransformation.setToIdentity();
POOL.recyclePoolItem(pTransformation);
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 10:47:33 - 11.05.2010
*/
public enum HorizontalAlign {
// ===========================================================
// Elements
// ===========================================================
LEFT,
CENTER,
RIGHT;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;
import java.net.Socket;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 14:42:15 - 18.09.2009
*/
public class SocketUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void closeSocket(final DatagramSocket pDatagramSocket) {
if(pDatagramSocket != null && !pDatagramSocket.isClosed()) {
pDatagramSocket.close();
}
}
public static void closeSocket(final Socket pSocket) {
if(pSocket != null && !pSocket.isClosed()) {
try {
pSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
public static void closeSocket(final ServerSocket pServerSocket) {
if(pServerSocket != null && !pServerSocket.isClosed()) {
try {
pServerSocket.close();
} catch (final IOException e) {
Debug.e(e);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.concurrent.Callable;
import org.anddev.andengine.ui.activity.BaseActivity.CancelledException;
import org.anddev.andengine.util.progress.IProgressListener;
import org.anddev.andengine.util.progress.ProgressCallable;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.AsyncTask;
import android.view.Window;
import android.view.WindowManager;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 18:11:54 - 07.03.2011
*/
public class ActivityUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void requestFullscreen(final Activity pActivity) {
final Window window = pActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
window.requestFeature(Window.FEATURE_NO_TITLE);
}
/**
* @param pActivity
* @param pScreenBrightness [0..1]
*/
public static void setScreenBrightness(final Activity pActivity, final float pScreenBrightness) {
final Window window = pActivity.getWindow();
final WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
windowLayoutParams.screenBrightness = pScreenBrightness;
window.setAttributes(windowLayoutParams);
}
public static void keepScreenOn(final Activity pActivity) {
pActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, null, pCancelable);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitleResID, pMessageResID, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
ActivityUtils.doAsync(pContext, pTitle, pMessage, pCallable, pCallback, pExceptionCallback, false);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
ActivityUtils.doAsync(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID), pCallable, pCallback, pExceptionCallback, pCancelable);
}
public static <T> void doAsync(final Context pContext, final CharSequence pTitle, final CharSequence pMessage, final Callable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback, final boolean pCancelable) {
new AsyncTask<Void, Void, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = ProgressDialog.show(pContext, pTitle, pMessage, true, pCancelable);
if(pCancelable) {
this.mPD.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(final DialogInterface pDialogInterface) {
pExceptionCallback.onCallback(new CancelledException());
pDialogInterface.dismiss();
}
});
}
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call();
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback) {
ActivityUtils.doProgressAsync(pContext, pTitleResID, pCallable, pCallback, null);
}
public static <T> void doProgressAsync(final Context pContext, final int pTitleResID, final ProgressCallable<T> pCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
new AsyncTask<Void, Integer, T>() {
private ProgressDialog mPD;
private Exception mException = null;
@Override
public void onPreExecute() {
this.mPD = new ProgressDialog(pContext);
this.mPD.setTitle(pTitleResID);
this.mPD.setIcon(android.R.drawable.ic_menu_save);
this.mPD.setIndeterminate(false);
this.mPD.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.mPD.show();
super.onPreExecute();
}
@Override
public T doInBackground(final Void... params) {
try {
return pCallable.call(new IProgressListener() {
@Override
public void onProgressChanged(final int pProgress) {
onProgressUpdate(pProgress);
}
});
} catch (final Exception e) {
this.mException = e;
}
return null;
}
@Override
public void onProgressUpdate(final Integer... values) {
this.mPD.setProgress(values[0]);
}
@Override
public void onPostExecute(final T result) {
try {
this.mPD.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
if(this.isCancelled()) {
this.mException = new CancelledException();
}
if(this.mException == null) {
pCallback.onCallback(result);
} else {
if(pExceptionCallback == null) {
Debug.e("Error", this.mException);
} else {
pExceptionCallback.onCallback(this.mException);
}
}
super.onPostExecute(result);
}
}.execute((Void[]) null);
}
public static <T> void doAsync(final Context pContext, final int pTitleResID, final int pMessageResID, final AsyncCallable<T> pAsyncCallable, final Callback<T> pCallback, final Callback<Exception> pExceptionCallback) {
final ProgressDialog pd = ProgressDialog.show(pContext, pContext.getString(pTitleResID), pContext.getString(pMessageResID));
pAsyncCallable.call(new Callback<T>() {
@Override
public void onCallback(final T result) {
try {
pd.dismiss();
} catch (final Exception e) {
Debug.e("Error", e);
/* Nothing. */
}
pCallback.onCallback(result);
}
}, pExceptionCallback);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.HashMap;
import java.util.Iterator;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 16:54:24 - 07.11.2010
*/
public class MultiKeyHashMap<K, V> extends HashMap<MultiKey<K>, V> {
// ===========================================================
// Constants
// ==========================================================
private static final long serialVersionUID = -6262447639526561122L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public V get(final K ... pKeys) {
final int hashCode = MultiKey.hash(pKeys);
final Iterator<Entry<MultiKey<K>, V>> it = this.entrySet().iterator();
while(it.hasNext()) {
final Entry<MultiKey<K>, V> entry = it.next();
final MultiKey<K> entryKey = entry.getKey();
if (entryKey.hashCode() == hashCode && this.isEqualKey(entryKey.getKeys(), pKeys)) {
return entry.getValue();
}
}
return null;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private boolean isEqualKey(final K[] pKeysA, final K[] pKeysB) {
if (pKeysA.length != pKeysB.length) {
return false;
} else {
for (int i = 0; i < pKeysA.length; i++) {
final K keyA = pKeysA[i];
final K keyB = pKeysB[i];
if(keyA == null) {
if(keyB != null) {
return false;
}
} else {
if(!keyA.equals(keyB)) {
return false;
}
}
}
}
return true;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.GregorianCalendar;
import org.anddev.andengine.util.constants.Constants;
import android.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:43:32 - 02.11.2010
*/
public class BetaUtils implements Constants {
// ===========================================================
// Constants
// ===========================================================
private static final String PREFERENCES_BETAUTILS_ID = "preferences.betautils.lastuse";
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID) {
return BetaUtils.finishWhenExpired(pActivity, pExpirationDate, pTitleResourceID, pMessageResourceID, null, null);
}
public static boolean finishWhenExpired(final Activity pActivity, final GregorianCalendar pExpirationDate, final int pTitleResourceID, final int pMessageResourceID, final Intent pOkIntent, final Intent pCancelIntent) {
final SharedPreferences spref = SimplePreferences.getInstance(pActivity);
final long now = System.currentTimeMillis();
final long lastuse = Math.max(now, spref.getLong(PREFERENCES_BETAUTILS_ID, -1));
spref.edit().putLong(PREFERENCES_BETAUTILS_ID, lastuse).commit();
final GregorianCalendar lastuseDate = new GregorianCalendar();
lastuseDate.setTimeInMillis(lastuse);
if(lastuseDate.after(pExpirationDate)){
final Builder alertDialogBuilder = new AlertDialog.Builder(pActivity)
.setTitle(pTitleResourceID)
.setIcon(R.drawable.ic_dialog_alert)
.setMessage(pMessageResourceID);
alertDialogBuilder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener(){
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
if(pOkIntent != null) {
pActivity.startActivity(pOkIntent);
}
pActivity.finish();
}
});
alertDialogBuilder.setNegativeButton(android.R.string.cancel, new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
if(pCancelIntent != null) {
pActivity.startActivity(pCancelIntent);
}
pActivity.finish();
}
})
.create().show();
return true;
}else{
return false;
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 09:40:55 - 14.12.2009S
*/
public interface Callback<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public void onCallback(final T pCallbackValue);
} | Java |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:43:39 - 11.03.2010
*/
public class ListUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static <T> ArrayList<? extends T> toList(final T pItem) {
final ArrayList<T> out = new ArrayList<T>();
out.add(pItem);
return out;
}
public static <T> ArrayList<? extends T> toList(final T ... pItems) {
final ArrayList<T> out = new ArrayList<T>();
final int itemCount = pItems.length;
for(int i = 0; i < itemCount; i++) {
out.add(pItems[i]);
}
return out;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import org.anddev.andengine.util.Debug;
/**
* (c) Zynga 2011
*
* @author Nicolas Gramlich <ngramlich@zynga.com>
* @since 02:19:02 - 14.08.2011
*/
public class ByteBufferOutputStream extends OutputStream {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
protected final int mMaximumGrow;
protected byte mData[];
protected int mCount;
// ===========================================================
// Constructors
// ===========================================================
public ByteBufferOutputStream(final int pInitialCapacity, final int pMaximumGrow) {
this.mMaximumGrow = pMaximumGrow;
this.mData = new byte[pInitialCapacity];
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public void write(final int pByte) {
this.ensureCapacity(this.mCount + 1);
this.mData[this.mCount] = (byte) pByte;
this.mCount += 1;
}
@Override
public void write(final byte pData[], final int pOffset, final int pLength) {
this.ensureCapacity(this.mCount + pLength);
System.arraycopy(pData, pOffset, this.mData, this.mCount, pLength);
this.mCount += pLength;
}
@Override
public void close() throws IOException {
}
// ===========================================================
// Methods
// ===========================================================
private void ensureCapacity(final int pDesiredCapacity) {
if(pDesiredCapacity - this.mData.length > 0) {
this.grow(pDesiredCapacity);
}
}
private void grow(final int pDesiredCapacity) {
final int oldCapacity = this.mData.length;
final int grow = Math.min(this.mMaximumGrow, oldCapacity);
Debug.d("Growing by: " + grow);
int newCapacity = oldCapacity + grow;
if(newCapacity - pDesiredCapacity < 0) {
newCapacity = pDesiredCapacity;
}
if(newCapacity < 0) {
if(pDesiredCapacity < 0) {
throw new OutOfMemoryError();
} else {
newCapacity = Integer.MAX_VALUE;
}
}
final byte[] data = new byte[newCapacity];
System.arraycopy(this.mData, 0, data, 0, this.mCount);
this.mData = data;
}
public ByteBuffer toByteBuffer() {
return ByteBuffer.wrap(this.mData, 0, this.mCount).slice();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | Java |
package org.anddev.andengine.util;
import org.anddev.andengine.util.constants.Constants;
import android.util.Log;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:29:16 - 08.03.2010
*/
public class Debug implements Constants {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
private static String sDebugTag = DEBUGTAG;
private static DebugLevel sDebugLevel = DebugLevel.VERBOSE;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public static String getDebugTag() {
return Debug.sDebugTag;
}
public static void setDebugTag(final String pDebugTag) {
Debug.sDebugTag = pDebugTag;
}
public static DebugLevel getDebugLevel() {
return Debug.sDebugLevel;
}
public static void setDebugLevel(final DebugLevel pDebugLevel) {
if(pDebugLevel == null) {
throw new IllegalArgumentException("pDebugLevel must not be null!");
}
Debug.sDebugLevel = pDebugLevel;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void v(final String pMessage) {
Debug.v(pMessage, null);
}
public static void v(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.VERBOSE)) {
Log.v(sDebugTag, pMessage, pThrowable);
}
}
public static void d(final String pMessage) {
Debug.d(pMessage, null);
}
public static void d(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.DEBUG)) {
Log.d(sDebugTag, pMessage, pThrowable);
}
}
public static void i(final String pMessage) {
Debug.i(pMessage, null);
}
public static void i(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.INFO)) {
Log.i(sDebugTag, pMessage, pThrowable);
}
}
public static void w(final String pMessage) {
Debug.w(pMessage, null);
}
public static void w(final Throwable pThrowable) {
Debug.w("", pThrowable);
}
public static void w(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.WARNING)) {
if(pThrowable == null) {
Log.w(sDebugTag, pMessage, new Exception());
} else {
Log.w(sDebugTag, pMessage, pThrowable);
}
}
}
public static void e(final String pMessage) {
Debug.e(pMessage, null);
}
public static void e(final Throwable pThrowable) {
Debug.e(sDebugTag, pThrowable);
}
public static void e(final String pMessage, final Throwable pThrowable) {
if(sDebugLevel.isSameOrLessThan(DebugLevel.ERROR)) {
if(pThrowable == null) {
Log.e(sDebugTag, pMessage, new Exception());
} else {
Log.e(sDebugTag, pMessage, pThrowable);
}
}
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static enum DebugLevel implements Comparable<DebugLevel> {
NONE,
ERROR,
WARNING,
INFO,
DEBUG,
VERBOSE;
public static DebugLevel ALL = DebugLevel.VERBOSE;
private boolean isSameOrLessThan(final DebugLevel pDebugLevel) {
return this.compareTo(pDebugLevel) >= 0;
}
}
}
| Java |
package org.anddev.andengine.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;
import android.os.Environment;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 13:53:33 - 20.06.2010
*/
public class FileUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static void copyToExternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToExternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final int pSourceResourceID, final String pFilename) throws FileNotFoundException {
FileUtils.copyToInternalStorage(pContext, pContext.getResources().openRawResource(pSourceResourceID), pFilename);
}
public static void copyToExternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToExternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
public static void copyToInternalStorage(final Context pContext, final String pSourceAssetPath, final String pFilename) throws IOException {
FileUtils.copyToInternalStorage(pContext, pContext.getAssets().open(pSourceAssetPath), pFilename);
}
private static void copyToInternalStorage(final Context pContext, final InputStream pInputStream, final String pFilename) throws FileNotFoundException {
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(new File(pContext.getFilesDir(), pFilename)));
}
public static void copyToExternalStorage(final Context pContext, final InputStream pInputStream, final String pFilePath) throws FileNotFoundException {
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
StreamUtils.copyAndClose(pInputStream, new FileOutputStream(absoluteFilePath));
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static boolean isFileExistingOnExternalStorage(final Context pContext, final String pFilePath) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
final File file = new File(absoluteFilePath);
return file.exists()&& file.isFile();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean isDirectoryExistingOnExternalStorage(final Context pContext, final String pDirectory) {
if (FileUtils.isExternalStorageReadable()) {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
final File file = new File(absoluteFilePath);
return file.exists() && file.isDirectory();
} else {
throw new IllegalStateException("External Storage is not readable.");
}
}
public static boolean ensureDirectoriesExistOnExternalStorage(final Context pContext, final String pDirectory) {
if(FileUtils.isDirectoryExistingOnExternalStorage(pContext, pDirectory)) {
return true;
}
if (FileUtils.isExternalStorageWriteable()) {
final String absoluteDirectoryPath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pDirectory);
return new File(absoluteDirectoryPath).mkdirs();
} else {
throw new IllegalStateException("External Storage is not writeable.");
}
}
public static InputStream openOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new FileInputStream(absoluteFilePath);
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list();
}
public static String[] getDirectoryListOnExternalStorage(final Context pContext, final String pFilePath, final FilenameFilter pFilenameFilter) throws FileNotFoundException {
final String absoluteFilePath = FileUtils.getAbsolutePathOnExternalStorage(pContext, pFilePath);
return new File(absoluteFilePath).list(pFilenameFilter);
}
public static String getAbsolutePathOnInternalStorage(final Context pContext, final String pFilePath) {
return pContext.getFilesDir().getAbsolutePath() + pFilePath;
}
public static String getAbsolutePathOnExternalStorage(final Context pContext, final String pFilePath) {
return Environment.getExternalStorageDirectory() + "/Android/data/" + pContext.getApplicationInfo().packageName + "/files/" + pFilePath;
}
public static boolean isExternalStorageWriteable() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
public static boolean isExternalStorageReadable() {
final String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
}
public static void copyFile(final File pIn, final File pOut) throws IOException {
final FileInputStream fis = new FileInputStream(pIn);
final FileOutputStream fos = new FileOutputStream(pOut);
try {
StreamUtils.copy(fis, fos);
} finally {
StreamUtils.close(fis);
StreamUtils.close(fos);
}
}
/**
* Deletes all files and sub-directories under <code>dir</code>. Returns
* true if all deletions were successful. If a deletion fails, the method
* stops attempting to delete and returns false.
*
* @param pFileOrDirectory
* @return
*/
public static boolean deleteDirectory(final File pFileOrDirectory) {
if(pFileOrDirectory.isDirectory()) {
final String[] children = pFileOrDirectory.list();
final int childrenCount = children.length;
for(int i = 0; i < childrenCount; i++) {
final boolean success = FileUtils.deleteDirectory(new File(pFileOrDirectory, children[i]));
if(!success) {
return false;
}
}
}
// The directory is now empty so delete it
return pFileOrDirectory.delete();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:00:30 - 14.05.2010
* @param <T>
*/
public interface AsyncCallable<T> {
// ===========================================================
// Final Fields
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
* Computes a result asynchronously, return values and exceptions are to be handled through the callbacks.
* This method is expected to return almost immediately, after starting a {@link Thread} or similar.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
public void call(final Callback<T> pCallback, final Callback<Exception> pExceptionCallback);
} | Java |
package org.anddev.andengine.util;
import org.xml.sax.Attributes;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:02:09 - 21.07.2010
*/
public class SAXUtils {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static String getAttribute(final Attributes pAttributes, final String pAttributeName, final String pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? value : pDefaultValue;
}
public static String getAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
final String value = pAttributes.getValue("", pAttributeName);
if(value != null) {
return value;
} else {
throw new IllegalArgumentException("No value found for attribute: '" + pAttributeName + "'");
}
}
public static boolean getBooleanAttribute(final Attributes pAttributes, final String pAttributeName, final boolean pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Boolean.parseBoolean(value) : pDefaultValue;
}
public static boolean getBooleanAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Boolean.parseBoolean(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static byte getByteAttribute(final Attributes pAttributes, final String pAttributeName, final byte pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Byte.parseByte(value) : pDefaultValue;
}
public static byte getByteAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Byte.parseByte(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static short getShortAttribute(final Attributes pAttributes, final String pAttributeName, final short pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Short.parseShort(value) : pDefaultValue;
}
public static short getShortAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Short.parseShort(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static int getIntAttribute(final Attributes pAttributes, final String pAttributeName, final int pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Integer.parseInt(value) : pDefaultValue;
}
public static int getIntAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Integer.parseInt(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static long getLongAttribute(final Attributes pAttributes, final String pAttributeName, final long pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Long.parseLong(value) : pDefaultValue;
}
public static long getLongAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Long.parseLong(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static float getFloatAttribute(final Attributes pAttributes, final String pAttributeName, final float pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Float.parseFloat(value) : pDefaultValue;
}
public static float getFloatAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Float.parseFloat(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static double getDoubleAttribute(final Attributes pAttributes, final String pAttributeName, final double pDefaultValue) {
final String value = pAttributes.getValue("", pAttributeName);
return (value != null) ? Double.parseDouble(value) : pDefaultValue;
}
public static double getDoubleAttributeOrThrow(final Attributes pAttributes, final String pAttributeName) {
return Double.parseDouble(SAXUtils.getAttributeOrThrow(pAttributes, pAttributeName));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final boolean pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final byte pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final short pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final int pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final long pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final float pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final double pValue) {
SAXUtils.appendAttribute(pStringBuilder, pName, String.valueOf(pValue));
}
public static void appendAttribute(final StringBuilder pStringBuilder, final String pName, final String pValue) {
pStringBuilder.append(' ').append(pName).append('=').append('\"').append(pValue).append('\"');
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.Random;
import org.anddev.andengine.util.constants.MathConstants;
import android.util.FloatMath;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 20:42:15 - 17.12.2009
*/
public class MathUtils implements MathConstants {
// ===========================================================
// Constants
// ===========================================================
public static Random RANDOM = new Random(System.nanoTime());
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public static float atan2(final float dY, final float dX) {
return (float)Math.atan2(dY, dX);
}
public static final float radToDeg(final float pRad) {
return RAD_TO_DEG * pRad;
}
public static final float degToRad(final float pDegree) {
return DEG_TO_RAD * pDegree;
}
public static final int randomSign() {
if(RANDOM.nextBoolean()) {
return 1;
} else {
return -1;
}
}
public static final float random(final float pMin, final float pMax) {
return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
/**
* @param pMin inclusive!
* @param pMax inclusive!
* @return
*/
public static final int random(final int pMin, final int pMax) {
return pMin + RANDOM.nextInt(pMax - pMin + 1);
}
public static final boolean isPowerOfTwo(final int n) {
return ((n != 0) && (n & (n - 1)) == 0);
}
public static final int nextPowerOfTwo(final float f) {
return MathUtils.nextPowerOfTwo((int)(Math.ceil(f)));
}
public static final int nextPowerOfTwo(final int n) {
int k = n;
if (k == 0) {
return 1;
}
k--;
for (int i = 1; i < 32; i <<= 1) {
k = k | k >> i;
}
return k + 1;
}
public static final int sum(final int[] pValues) {
int sum = 0;
for(int i = pValues.length - 1; i >= 0; i--) {
sum += pValues[i];
}
return sum;
}
public static final void arraySumInternal(final int[] pValues) {
final int valueCount = pValues.length;
for(int i = 1; i < valueCount; i++) {
pValues[i] = pValues[i-1] + pValues[i];
}
}
public static final void arraySumInternal(final long[] pValues) {
final int valueCount = pValues.length;
for(int i = 1; i < valueCount; i++) {
pValues[i] = pValues[i-1] + pValues[i];
}
}
public static final void arraySumInternal(final long[] pValues, final long pFactor) {
pValues[0] = pValues[0] * pFactor;
final int valueCount = pValues.length;
for(int i = 1; i < valueCount; i++) {
pValues[i] = pValues[i-1] + pValues[i] * pFactor;
}
}
public static final void arraySumInto(final long[] pValues, final long[] pTargetValues, final long pFactor) {
pTargetValues[0] = pValues[0] * pFactor;
final int valueCount = pValues.length;
for(int i = 1; i < valueCount; i++) {
pTargetValues[i] = pTargetValues[i-1] + pValues[i] * pFactor;
}
}
public static final float arraySum(final float[] pValues) {
float sum = 0;
final int valueCount = pValues.length;
for(int i = 0; i < valueCount; i++) {
sum += pValues[i];
}
return sum;
}
public static final float arrayAverage(final float[] pValues) {
return MathUtils.arraySum(pValues) / pValues.length;
}
public static float[] rotateAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY) {
if(pRotation != 0) {
final float rotationRad = MathUtils.degToRad(pRotation);
final float sinRotationRad = FloatMath.sin(rotationRad);
final float cosRotationInRad = FloatMath.cos(rotationRad);
for(int i = pVertices.length - 2; i >= 0; i -= 2) {
final float pX = pVertices[i];
final float pY = pVertices[i + 1];
pVertices[i] = pRotationCenterX + (cosRotationInRad * (pX - pRotationCenterX) - sinRotationRad * (pY - pRotationCenterY));
pVertices[i + 1] = pRotationCenterY + (sinRotationRad * (pX - pRotationCenterX) + cosRotationInRad * (pY - pRotationCenterY));
}
}
return pVertices;
}
public static float[] scaleAroundCenter(final float[] pVertices, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) {
if(pScaleX != 1 || pScaleY != 1) {
for(int i = pVertices.length - 2; i >= 0; i -= 2) {
pVertices[i] = pScaleCenterX + (pVertices[i] - pScaleCenterX) * pScaleX;
pVertices[i + 1] = pScaleCenterY + (pVertices[i + 1] - pScaleCenterY) * pScaleY;
}
}
return pVertices;
}
public static float[] rotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) {
MathUtils.rotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY);
return MathUtils.scaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY);
}
public static float[] revertScaleAroundCenter(final float[] pVertices, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) {
return MathUtils.scaleAroundCenter(pVertices, 1 / pScaleX, 1 / pScaleY, pScaleCenterX, pScaleCenterY);
}
public static float[] revertRotateAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY) {
return MathUtils.rotateAroundCenter(pVertices, -pRotation, pRotationCenterX, pRotationCenterY);
}
public static float[] revertRotateAndScaleAroundCenter(final float[] pVertices, final float pRotation, final float pRotationCenterX, final float pRotationCenterY, final float pScaleX, final float pScaleY, final float pScaleCenterX, final float pScaleCenterY) {
MathUtils.revertScaleAroundCenter(pVertices, pScaleX, pScaleY, pScaleCenterX, pScaleCenterY);
return MathUtils.revertRotateAroundCenter(pVertices, pRotation, pRotationCenterX, pRotationCenterY);
}
public static int bringToBounds(final int pMinValue, final int pMaxValue, final int pValue) {
return Math.max(pMinValue, Math.min(pMaxValue, pValue));
}
public static float bringToBounds(final float pMinValue, final float pMaxValue, final float pValue) {
return Math.max(pMinValue, Math.min(pMaxValue, pValue));
}
public static float distance(final float pX1, final float pY1, final float pX2, final float pY2){
final float dX = pX2 - pX1;
final float dY = pY2 - pY1;
return FloatMath.sqrt((dX * dX) + (dY * dY));
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
import java.util.ArrayList;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 22:20:08 - 27.12.2010
*/
public class SmartList<T> extends ArrayList<T> {
// ===========================================================
// Constants
// ===========================================================
private static final long serialVersionUID = -8335986399182700102L;
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
public SmartList() {
}
public SmartList(final int pCapacity) {
super(pCapacity);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
/**
* @param pItem the item to remove.
* @param pParameterCallable to be called with the removed item, if it was removed.
*/
public boolean remove(final T pItem, final ParameterCallable<T> pParameterCallable) {
final boolean removed = this.remove(pItem);
if(removed) {
pParameterCallable.call(pItem);
}
return removed;
}
public T remove(final IMatcher<T> pMatcher) {
for(int i = 0; i < this.size(); i++) {
if(pMatcher.matches(this.get(i))) {
return this.remove(i);
}
}
return null;
}
public T remove(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
return removed;
}
}
return null;
}
public boolean removeAll(final IMatcher<T> pMatcher) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
this.remove(i);
result = true;
}
}
return result;
}
/**
* @param pMatcher to find the items.
* @param pParameterCallable to be called with each matched item after it was removed.
*/
public boolean removeAll(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
boolean result = false;
for(int i = this.size() - 1; i >= 0; i--) {
if(pMatcher.matches(this.get(i))) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
result = true;
}
}
return result;
}
public void clear(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T removed = this.remove(i);
pParameterCallable.call(removed);
}
}
public T find(final IMatcher<T> pMatcher) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
return item;
}
}
return null;
}
public void call(final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
pParameterCallable.call(item);
}
}
public void call(final IMatcher<T> pMatcher, final ParameterCallable<T> pParameterCallable) {
for(int i = this.size() - 1; i >= 0; i--) {
final T item = this.get(i);
if(pMatcher.matches(item)) {
pParameterCallable.call(item);
}
}
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 15:15:23 - 24.07.2010
*/
public enum VerticalAlign {
// ===========================================================
// Elements
// ===========================================================
TOP,
CENTER,
BOTTOM;
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| Java |
package org.anddev.andengine.util;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:32:22 - 26.12.2010
*/
public interface IMatcher<T> {
// ===========================================================
// Constants
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
public boolean matches(final T pObject);
}
| Java |
package jp.co.so2.pinch;
import org.appcelerator.kroll.KrollDict;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.view.TiUIView;
import android.content.Context;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener;
import android.view.View;
public class UIPinchView extends TiUIView
{
public PinchView tiPinchView;
private float maxZoom = 5.f;
private float minZoom = 0.1f;
private float curZoom = 1.f;
public UIPinchView(TiViewProxy proxy)
{
super(proxy);
setNativeView(tiPinchView = new PinchView(proxy.getActivity()));
}
@Override
public void processProperties(KrollDict d) {
super.processProperties(d);
if(d.containsKeyAndNotNull("maxZoomValue"))
maxZoom = d.getDouble("maxZoomValue").floatValue();
if(d.containsKeyAndNotNull("minZoomValue"))
minZoom = d.getDouble("minZoomValue").floatValue();
}
public void setMaxZoomValue(float maxZoom)
{
this.maxZoom = maxZoom;
}
public void setMinZoomValue(float minZoom)
{
this.minZoom = minZoom;
}
public void setCurZoomValue(float curZoom)
{
this.curZoom = curZoom;
}
public class PinchView extends View {
private static final int INVALID_POINTER_ID = -1;
private int activePointerId;
private ScaleGestureDetector pinchDetector;
private float lastX, lastY;
public PinchView(Context c)
{
super(c);
if(c.getPackageManager().hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH))
pinchDetector = new ScaleGestureDetector(c, new ScaleListener());
else
Log.i("UIPinchView","Multitouch not supported on this device!");
}
@Override
public boolean onTouchEvent(MotionEvent e)
{
if(pinchDetector != null)
pinchDetector.onTouchEvent(e);
final int action = e.getAction();
KrollDict eventData = new KrollDict();
switch(action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = e.getX();
final float y = e.getY();
eventData.put("x", e.getX());
eventData.put("y", e.getY());
proxy.fireEvent("multiStart", eventData);
activePointerId = e.getPointerId(0);
lastX = x;
lastY = y;
break;
}
case MotionEvent.ACTION_MOVE: {
final int pointerIndex = e.findPointerIndex(activePointerId);
if(pointerIndex == INVALID_POINTER_ID)
break;
final float x = e.getX(pointerIndex);
final float y = e.getY(pointerIndex);
if(pinchDetector == null || !pinchDetector.isInProgress())
{
eventData.put("x", x - lastX);
eventData.put("y", y - lastY);
proxy.fireEvent("multiMove", eventData);
}
lastX = x;
lastY = y;
break;
}
case MotionEvent.ACTION_UP: {
activePointerId = INVALID_POINTER_ID;
eventData.put("x", e.getX());
eventData.put("y", e.getY());
proxy.fireEvent("multiEnd", eventData);
break;
}
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (e.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = e.getPointerId(pointerIndex);
if(pointerId == activePointerId) {
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
activePointerId = e.getPointerId(newPointerIndex);
lastX = e.getX(newPointerIndex);
lastY = e.getY(newPointerIndex);
}
break;
}
}
return true;
}
private class ScaleListener extends SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
curZoom *= detector.getScaleFactor();
curZoom = Math.max(minZoom, Math.min(curZoom, maxZoom));
invalidate();
KrollDict eventData = new KrollDict();
eventData.put("scale", curZoom);
proxy.fireEvent("pinch", eventData);
return true;
}
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Room;
import com.google.android.apps.iosched.io.model.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class RoomsHandler extends JSONHandler {
private static final String TAG = makeLogTag(RoomsHandler.class);
public RoomsHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Rooms roomsJson = new Gson().fromJson(json, Rooms.class);
int noOfRooms = roomsJson.rooms.length;
for (int i = 0; i < noOfRooms; i++) {
parseRoom(roomsJson.rooms[i], batch);
}
return batch;
}
private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Rooms.CONTENT_URI));
builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id);
builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name);
builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SearchSuggestions {
public String[] words;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Tracks {
Track[] track;
public Track[] getTrack() {
return track;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class TimeSlot {
public String start;
public String end;
public String title;
public String type;
public String meta;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class EventSlots {
public Day[] day;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Room {
public String id;
public String name;
public String floor;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Track {
public String id;
public String name;
public String color;
@SerializedName("abstract")
public String _abstract;
public int level;
public int order_in_level;
public int meta;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Day {
public String date;
public TimeSlot[] slot;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Rooms {
public Room[] rooms;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.map.model;
import java.util.Map;
public class MapResponse {
public MapConfig config;
public Map<String, Marker[]> markers;
public Map<String, Tile> tiles;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.map.model;
public class Tile {
public String filename;
public String url;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.map.model;
public class MapConfig {
public boolean enableMyLocation;
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.map.model;
public class Marker {
public String id;
public String type;
public float lat;
public float lng;
public String title;
public String track;
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.SearchSuggestions;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.app.SearchManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
public class SearchSuggestHandler extends JSONHandler {
public SearchSuggestHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class);
if (suggestions.words != null) {
// Clear out suggestions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.build());
// Rebuild suggestions
for (String word : suggestions.words) {
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word)
.build());
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import java.io.IOException;
/**
* General {@link IOException} that indicates a problem occurred while parsing or applying a {@link
* JSONHandler}.
*/
public class HandlerException extends IOException {
public HandlerException() {
super();
}
public HandlerException(String message) {
super(message);
}
public HandlerException(String message, Throwable cause) {
super(message);
initCause(cause);
}
@Override
public String toString() {
if (getCause() != null) {
return getLocalizedMessage() + ": " + getCause();
} else {
return getLocalizedMessage();
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase;
import com.google.android.apps.iosched.util.*;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.SessionResponse;
import com.google.api.services.googledevelopers.model.SessionsResponse;
import com.google.api.services.googledevelopers.model.TrackResponse;
import com.google.api.services.googledevelopers.model.TracksResponse;
import java.io.IOException;
import java.util.*;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import static com.google.android.apps.iosched.util.LogUtils.*;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
public class SessionsHandler {
private static final String TAG = makeLogTag(SessionsHandler.class);
private static final String BASE_SESSION_URL
= "https://developers.google.com/events/io/sessions/";
private static final String EVENT_TYPE_KEYNOTE = Sessions.SESSION_TYPE_KEYNOTE;
private static final String EVENT_TYPE_OFFICE_HOURS = Sessions.SESSION_TYPE_OFFICE_HOURS;
private static final String EVENT_TYPE_CODELAB = Sessions.SESSION_TYPE_CODELAB;
private static final String EVENT_TYPE_SANDBOX = Sessions.SESSION_TYPE_SANDBOX;
private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1;
private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2;
private Context mContext;
public SessionsHandler(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> fetchAndParse(
Googledevelopers conferenceAPI)
throws IOException {
// Set up the HTTP transport and JSON factory
SessionsResponse sessions;
SessionsResponse starredSessions = null;
TracksResponse tracks;
try {
sessions = conferenceAPI.events().sessions().list(Config.EVENT_ID).setLimit(9999L).execute();
tracks = conferenceAPI.events().tracks().list(Config.EVENT_ID).execute();
if (sessions == null || sessions.getSessions() == null) {
throw new HandlerException("Sessions list was null.");
}
if (tracks == null || tracks.getTracks() == null) {
throw new HandlerException("trackDetails list was null.");
}
} catch (HandlerException e) {
LOGE(TAG, "Fatal: error fetching sessions/tracks", e);
return Lists.newArrayList();
}
final boolean profileAvailableBefore = PrefUtils.isDevsiteProfileAvailable(mContext);
boolean profileAvailableNow = false;
try {
starredSessions = conferenceAPI.users().events().sessions().list(Config.EVENT_ID).execute();
// If this succeeded, the user has a DevSite profile
PrefUtils.markDevSiteProfileAvailable(mContext, true);
profileAvailableNow = true;
} catch (GoogleJsonResponseException e) {
// Hack: If the user doesn't have a developers.google.com profile, the Conference API
// will respond with HTTP 401 and include something like
// "Provided user does not have a developers.google.com profile" in the message.
if (401 == e.getStatusCode()
&& e.getDetails() != null
&& e.getDetails().getMessage() != null
&& e.getDetails().getMessage().contains("developers.google.com")) {
LOGE(TAG, "User does not have a developers.google.com profile. Not syncing remote " +
"personalized schedule.");
starredSessions = null;
// Record that the user's profile is offline. If this changes later, we'll re-upload any local
// starred sessions.
PrefUtils.markDevSiteProfileAvailable(mContext, false);
} else {
LOGW(TAG, "Auth token invalid, requesting refresh", e);
AccountUtils.refreshAuthToken(mContext);
}
}
if (profileAvailableNow && !profileAvailableBefore) {
LOGI(TAG, "developers.google.com mode change: DEVSITE_PROFILE_AVAILABLE=false -> true");
// User's DevSite profile has come into existence. Re-upload tracks.
ContentResolver cr = mContext.getContentResolver();
String[] projection = new String[] {ScheduleContract.Sessions.SESSION_ID, Sessions.SESSION_TITLE};
Cursor c = cr.query(ScheduleContract.BASE_CONTENT_URI.buildUpon().
appendPath("sessions").appendPath("starred").build(), projection, null, null, null);
if (c != null) {
c.moveToFirst();
while (!c.isAfterLast()) {
String id = c.getString(0);
String title = c.getString(1);
LOGI(TAG, "Adding session: (" + id + ") " + title);
Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(id);
SessionsHelper.uploadStarredSession(mContext, sessionUri, true);
c.moveToNext();
}
}
// Hack: Use local starred sessions for now, to give the new sessions time to take effect
// TODO(trevorjohns): Upload starred sessions should be synchronous to avoid this hack
starredSessions = null;
}
return buildContentProviderOperations(sessions, starredSessions, tracks);
}
public ArrayList<ContentProviderOperation> parseString(String sessionsJson, String tracksJson) {
JsonFactory jsonFactory = new GsonFactory();
try {
SessionsResponse sessions = jsonFactory.fromString(sessionsJson, SessionsResponse.class);
TracksResponse tracks =
jsonFactory.fromString(tracksJson, TracksResponse.class);
return buildContentProviderOperations(sessions, null, tracks);
} catch (IOException e) {
LOGE(TAG, "Error reading speakers from packaged data", e);
return Lists.newArrayList();
}
}
private ArrayList<ContentProviderOperation> buildContentProviderOperations(
SessionsResponse sessions,
SessionsResponse starredSessions,
TracksResponse tracks) {
// If there was no starred sessions response (e.g. there was an auth issue,
// or this is a local sync), keep all the locally starred sessions.
boolean retainLocallyStarredSessions = (starredSessions == null);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
// Build lookup table for starredSessions mappings
HashSet<String> starredSessionsMap = new HashSet<String>();
if (starredSessions != null) {
List<SessionResponse> starredSessionList =
starredSessions.getSessions();
if (starredSessionList != null) {
for (SessionResponse session : starredSessionList) {
String sessionId = session.getId();
starredSessionsMap.add(sessionId);
}
}
}
// Build lookup table for track mappings
// Assumes that sessions can only have one track. Not guarenteed by the Conference API,
// but is being enforced by conference organizer policy.
HashMap<String, TrackResponse> trackMap
= new HashMap<String, TrackResponse>();
if (tracks != null) {
for (TrackResponse track : tracks.getTracks()) {
List<String> sessionIds = track.getSessions();
if (sessionIds != null) {
for (String sessionId : sessionIds) {
trackMap.put(sessionId, track);
}
}
}
}
if (sessions != null) {
List<SessionResponse> sessionList = sessions.getSessions();
int numSessions = sessionList.size();
if (numSessions > 0) {
LOGI(TAG, "Updating sessions data");
Set<String> starredSessionIds = new HashSet<String>();
if (retainLocallyStarredSessions) {
Cursor starredSessionsCursor = mContext.getContentResolver().query(
Sessions.CONTENT_STARRED_URI,
new String[]{ScheduleContract.Sessions.SESSION_ID},
null, null, null);
while (starredSessionsCursor.moveToNext()) {
starredSessionIds.add(starredSessionsCursor.getString(0));
}
starredSessionsCursor.close();
}
// Clear out existing sessions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.build());
// Maintain a list of created session block IDs
Set<String> blockIds = new HashSet<String>();
// Maintain a map of insert operations for sandbox-only blocks
HashMap<String, ContentProviderOperation> sandboxBlocks = new HashMap<String, ContentProviderOperation>();
for (SessionResponse session : sessionList) {
int flags = 0;
String sessionId = session.getId();
if (retainLocallyStarredSessions) {
flags = (starredSessionIds.contains(sessionId)
? PARSE_FLAG_FORCE_SCHEDULE_ADD
: PARSE_FLAG_FORCE_SCHEDULE_REMOVE);
}
if (TextUtils.isEmpty(sessionId)) {
LOGW(TAG, "Found session with empty ID in API response.");
continue;
}
// Session title
String sessionTitle = session.getTitle();
String sessionSubtype = session.getSubtype();
if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
sessionTitle = mContext.getString(
R.string.codelab_title_template, sessionTitle);
}
// Whether or not it's in the schedule
boolean inSchedule = starredSessionsMap.contains(sessionId);
if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0
|| (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) {
inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0;
}
if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) {
// Keynotes are always in your schedule.
inSchedule = true;
}
// Clean up session abstract
String sessionAbstract = session.getDescription();
if (sessionAbstract != null) {
sessionAbstract = sessionAbstract.replace('\r', '\n');
}
// Hashtags
TrackResponse track = trackMap.get(sessionId);
String hashtag = null;
if (track != null) {
hashtag = ParserUtils.sanitizeId(track.getTitle());
}
boolean isLivestream = false;
try {
isLivestream = session.getIsLivestream();
} catch (NullPointerException ignored) {
}
String youtubeUrl = session.getYoutubeUrl();
// Get block id
long sessionStartTime = session.getStartTimestamp().longValue() * 1000;
long sessionEndTime = session.getEndTimestamp().longValue() * 1000;
String blockId = ScheduleContract.Blocks.generateBlockId(
sessionStartTime, sessionEndTime);
if (!blockIds.contains(blockId) && !EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// New non-sandbox block
if (sandboxBlocks.containsKey(blockId)) {
sandboxBlocks.remove(blockId);
}
String blockType;
String blockTitle;
if (EVENT_TYPE_KEYNOTE.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE;
blockTitle = mContext.getString(R.string.schedule_block_title_keynote);
} else if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_CODELAB;
blockTitle = mContext.getString(
R.string.schedule_block_title_code_labs);
} else if (EVENT_TYPE_OFFICE_HOURS.equals(sessionSubtype)) {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS;
blockTitle = mContext.getString(
R.string.schedule_block_title_office_hours);
} else {
blockType = ScheduleContract.Blocks.BLOCK_TYPE_SESSION;
blockTitle = mContext.getString(
R.string.schedule_block_title_sessions);
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
blockIds.add(blockId);
} else if (!sandboxBlocks.containsKey(blockId) && !blockIds.contains(blockId) && EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// New sandbox-only block, add insert operation to map
String blockType = ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX;
String blockTitle = mContext.getString(
R.string.schedule_block_title_sandbox);
sandboxBlocks.put(blockId,
ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
}
// Insert session info
final ContentProviderOperation.Builder builder;
if (EVENT_TYPE_SANDBOX.equals(sessionSubtype)) {
// Sandbox companies go in the special sandbox table
builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.Sandbox.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(ScheduleContract.Sandbox.COMPANY_ID, sessionId)
.withValue(ScheduleContract.Sandbox.COMPANY_NAME, sessionTitle)
.withValue(ScheduleContract.Sandbox.COMPANY_DESC, sessionAbstract)
.withValue(ScheduleContract.Sandbox.COMPANY_URL, makeSessionUrl(sessionId))
.withValue(ScheduleContract.Sandbox.COMPANY_LOGO_URL, session.getIconUrl())
.withValue(ScheduleContract.Sandbox.ROOM_ID, sanitizeId(session.getLocation()))
.withValue(ScheduleContract.Sandbox.TRACK_ID, (track != null ? track.getId() : null))
.withValue(ScheduleContract.Sandbox.BLOCK_ID, blockId);
batch.add(builder.build());
} else {
// All other fields go in the normal sessions table
builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Sessions.SESSION_ID, sessionId)
.withValue(Sessions.SESSION_TYPE, sessionSubtype)
.withValue(Sessions.SESSION_LEVEL, null) // Not available
.withValue(Sessions.SESSION_TITLE, sessionTitle)
.withValue(Sessions.SESSION_ABSTRACT, sessionAbstract)
.withValue(Sessions.SESSION_HASHTAGS, hashtag)
.withValue(Sessions.SESSION_TAGS, null) // Not available
.withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId))
.withValue(Sessions.SESSION_LIVESTREAM_URL,
isLivestream ? youtubeUrl : null)
.withValue(Sessions.SESSION_MODERATOR_URL, null) // Not available
.withValue(Sessions.SESSION_REQUIREMENTS, null) // Not available
.withValue(Sessions.SESSION_STARRED, inSchedule)
.withValue(Sessions.SESSION_YOUTUBE_URL,
isLivestream ? null : youtubeUrl)
.withValue(Sessions.SESSION_PDF_URL, null) // Not available
.withValue(Sessions.SESSION_NOTES_URL, null) // Not available
.withValue(Sessions.ROOM_ID, sanitizeId(session.getLocation()))
.withValue(Sessions.BLOCK_ID, blockId);
batch.add(builder.build());
}
// Replace all session speakers
final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId);
batch.add(ContentProviderOperation
.newDelete(ScheduleContract
.addCallerIsSyncAdapterParameter(sessionSpeakersUri))
.build());
List<String> presenterIds = session.getPresenterIds();
if (presenterIds != null) {
for (String presenterId : presenterIds) {
batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri)
.withValue(SessionsSpeakers.SESSION_ID, sessionId)
.withValue(SessionsSpeakers.SPEAKER_ID, presenterId).build());
}
}
// Add track mapping
if (track != null) {
String trackId = track.getId();
if (trackId != null) {
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId)
.withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, trackId).build());
}
}
// Codelabs: Add mapping to codelab table
if (EVENT_TYPE_CODELAB.equals(sessionSubtype)) {
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(ScheduleDatabase.SessionsTracks.SESSION_ID, sessionId)
.withValue(ScheduleDatabase.SessionsTracks.TRACK_ID, "CODE_LABS").build());
}
}
// Insert sandbox-only blocks
batch.addAll(sandboxBlocks.values());
}
}
return batch;
}
private String makeSessionUrl(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return null;
}
return BASE_SESSION_URL + sessionId;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.FeedbackResponse;
import com.google.api.services.googledevelopers.model.ModifyFeedbackRequest;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class FeedbackHandler {
private static final String TAG = makeLogTag(FeedbackHandler.class);
private Context mContext;
public FeedbackHandler(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> uploadNew(Googledevelopers conferenceApi) {
// Collect rows of feedback
Cursor feedbackCursor = mContext.getContentResolver().query(
ScheduleContract.Feedback.CONTENT_URI,
null, null, null, null);
int sessionIdIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_ID);
int ratingIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.SESSION_RATING);
int relIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_RELEVANCE);
int contentIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_CONTENT);
int speakerIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_SPEAKER);
int willUseIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.ANSWER_WILLUSE);
int commentsIndex = feedbackCursor.getColumnIndex(ScheduleContract.Feedback.COMMENTS);
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
while (feedbackCursor.moveToNext()) {
String sessionId = feedbackCursor.getString(sessionIdIndex);
LOGI(TAG, "Uploading feedback for: " + sessionId);
int rating = feedbackCursor.getInt(ratingIndex);
int answerRelevance = feedbackCursor.getInt(relIndex);
int answerContent = feedbackCursor.getInt(contentIndex);
int answerSpeaker = feedbackCursor.getInt(speakerIndex);
int answerWillUseRaw = feedbackCursor.getInt(willUseIndex);
boolean answerWillUse = (answerWillUseRaw != 0);
String comments = feedbackCursor.getString(commentsIndex);
ModifyFeedbackRequest feedbackRequest = new ModifyFeedbackRequest();
feedbackRequest.setOverallScore(rating);
feedbackRequest.setRelevancyScore(answerRelevance);
feedbackRequest.setContentScore(answerContent);
feedbackRequest.setSpeakerScore(answerSpeaker);
// In this case, -1 means the user didn't answer the question.
if (answerWillUseRaw != -1) {
feedbackRequest.setWillUse(answerWillUse);
}
// Only post something If the comments field isn't empty
if (comments != null && comments.length() > 0) {
feedbackRequest.setAdditionalFeedback(comments);
}
feedbackRequest.setSessionId(sessionId);
feedbackRequest.setEventId(Config.EVENT_ID);
try {
Googledevelopers.Events.Sessions.Feedback feedback = conferenceApi.events().sessions()
.feedback(Config.EVENT_ID, sessionId, feedbackRequest);
FeedbackResponse response = feedback.execute();
if (response != null) {
LOGI(TAG, "Successfully sent feedback for: " + sessionId + ", comment: " + comments);
} else {
LOGE(TAG, "Sending logs failed");
}
} catch (IOException ioe) {
LOGE(TAG, "Sending logs failed and caused IOE", ioe);
return batch;
}
}
feedbackCursor.close();
// Clear out feedback forms we've just uploaded
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Feedback.CONTENT_URI))
.build());
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.googledevelopers.Googledevelopers;
import com.google.api.services.googledevelopers.model.PresenterResponse;
import com.google.api.services.googledevelopers.model.PresentersResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import static com.google.android.apps.iosched.util.LogUtils.*;
public class SpeakersHandler {
private static final String TAG = makeLogTag(SpeakersHandler.class);
public SpeakersHandler(Context context) {}
public ArrayList<ContentProviderOperation> fetchAndParse(
Googledevelopers conferenceAPI)
throws IOException {
PresentersResponse presenters;
try {
presenters = conferenceAPI.events().presenters().list(Config.EVENT_ID).execute();
if (presenters == null || presenters.getPresenters() == null) {
throw new HandlerException("Speakers list was null.");
}
} catch (HandlerException e) {
LOGE(TAG, "Error fetching speakers", e);
return Lists.newArrayList();
}
return buildContentProviderOperations(presenters);
}
public ArrayList<ContentProviderOperation> parseString(String json) {
JsonFactory jsonFactory = new GsonFactory();
try {
PresentersResponse presenters = jsonFactory.fromString(json, PresentersResponse.class);
return buildContentProviderOperations(presenters);
} catch (IOException e) {
LOGE(TAG, "Error reading speakers from packaged data", e);
return Lists.newArrayList();
}
}
private ArrayList<ContentProviderOperation> buildContentProviderOperations(
PresentersResponse presenters) {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
if (presenters != null) {
List<PresenterResponse> presenterList = presenters.getPresenters();
int numSpeakers = presenterList.size();
if (numSpeakers > 0) {
LOGI(TAG, "Updating presenters data");
// Clear out existing speakers
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
Speakers.CONTENT_URI))
.build());
// Insert latest speaker data
for (PresenterResponse presenter : presenterList) {
// Hack: Fix speaker URL so that it's not being resized
// Depends on thumbnail URL being exactly in the format we want
String thumbnail = presenter.getThumbnailUrl();
if (thumbnail != null) {
thumbnail = thumbnail.replace("?sz=50", "?sz=100");
}
batch.add(ContentProviderOperation.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Speakers.SPEAKER_ID, presenter.getId())
.withValue(Speakers.SPEAKER_NAME, presenter.getName())
.withValue(Speakers.SPEAKER_ABSTRACT, presenter.getBio())
.withValue(Speakers.SPEAKER_IMAGE_URL, thumbnail)
.withValue(Speakers.SPEAKER_URL, presenter.getPlusoneUrl())
.build());
}
}
}
return batch;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.OperationApplicationException;
import android.os.RemoteException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
public abstract class JSONHandler {
protected static Context mContext;
public JSONHandler(Context context) {
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
public final void parseAndApply(String json) throws IOException {
try {
final ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch = parse(json);
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
}
public static String parseResource(Context context, int resource) throws IOException {
InputStream is = context.getResources().openRawResource(resource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Day;
import com.google.android.apps.iosched.io.model.EventSlots;
import com.google.android.apps.iosched.io.model.TimeSlot;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class BlocksHandler extends JSONHandler {
private static final String TAG = makeLogTag(BlocksHandler.class);
public BlocksHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
try {
Gson gson = new Gson();
EventSlots eventSlots = gson.fromJson(json, EventSlots.class);
int numDays = eventSlots.day.length;
//2011-05-10T07:00:00.000-07:00
for (int i = 0; i < numDays; i++) {
Day day = eventSlots.day[i];
String date = day.date;
TimeSlot[] timeSlots = day.slot;
for (TimeSlot timeSlot : timeSlots) {
parseSlot(date, timeSlot, batch);
}
}
} catch (Throwable e) {
LOGE(TAG, e.toString());
}
return batch;
}
private static void parseSlot(String date, TimeSlot slot,
ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI));
//LOGD(TAG, "Inside parseSlot:" + date + ", " + slot);
String start = slot.start;
String end = slot.end;
String type = Blocks.BLOCK_TYPE_GENERIC;
if (slot.type != null) {
type = slot.type;
}
String title = "N_D";
if (slot.title != null) {
title = slot.title;
}
String startTime = date + "T" + start + ":00.000-07:00";
String endTime = date + "T" + end + ":00.000-07:00";
LOGV(TAG, "startTime:" + startTime);
long startTimeL = ParserUtils.parseTime(startTime);
long endTimeL = ParserUtils.parseTime(endTime);
final String blockId = Blocks.generateBlockId(startTimeL, endTimeL);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "title:" + title);
LOGV(TAG, "start:" + startTimeL);
builder.withValue(Blocks.BLOCK_ID, blockId);
builder.withValue(Blocks.BLOCK_TITLE, title);
builder.withValue(Blocks.BLOCK_START, startTimeL);
builder.withValue(Blocks.BLOCK_END, endTimeL);
builder.withValue(Blocks.BLOCK_TYPE, type);
builder.withValue(Blocks.BLOCK_META, slot.meta);
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.Color;
import com.google.android.apps.iosched.io.model.Track;
import com.google.android.apps.iosched.io.model.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class TracksHandler extends JSONHandler {
private static final String TAG = makeLogTag(TracksHandler.class);
public TracksHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI)).build());
Tracks tracksJson = new Gson().fromJson(json, Tracks.class);
int noOfTracks = tracksJson.getTrack().length;
for (int i = 0; i < noOfTracks; i++) {
parseTrack(tracksJson.getTrack()[i], batch);
}
return batch;
}
private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI));
builder.withValue(ScheduleContract.Tracks.TRACK_ID, track.id);
builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name);
builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color));
builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract);
builder.withValue(ScheduleContract.Tracks.TRACK_LEVEL, track.level);
builder.withValue(ScheduleContract.Tracks.TRACK_ORDER_IN_LEVEL,
track.order_in_level);
builder.withValue(ScheduleContract.Tracks.TRACK_META, track.meta);
builder.withValue(ScheduleContract.Tracks.TRACK_HASHTAG, ParserUtils.sanitizeId(track.name));
batch.add(builder.build());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.util.Log;
import com.google.android.apps.iosched.io.map.model.MapConfig;
import com.google.android.apps.iosched.io.map.model.MapResponse;
import com.google.android.apps.iosched.io.map.model.Marker;
import com.google.android.apps.iosched.io.map.model.Tile;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.MapUtils;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapPropertyHandler extends JSONHandler {
private static final String TAG = makeLogTag(MapPropertyHandler.class);
private Collection<Tile> mTiles;
public MapPropertyHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
MapResponse mapJson = new Gson().fromJson(json, MapResponse.class);
parseTileOverlays(mapJson.tiles, batch, mContext);
parseMarkers(mapJson.markers, batch);
parseConfig(mapJson.config, mContext);
mTiles = mapJson.tiles.values();
return batch;
}
private void parseConfig(MapConfig config, Context mContext) {
boolean enableMyLocation = config.enableMyLocation;
MapUtils.setMyLocationEnabled(mContext,enableMyLocation);
}
private void parseMarkers(Map<String, Marker[]> markers,
ArrayList<ContentProviderOperation> batch) {
for (Entry<String, Marker[]> entry : markers.entrySet()) {
String floor = entry.getKey();
// add each Marker
for (Marker marker : entry.getValue()) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.MapMarkers.CONTENT_URI));
builder.withValue(ScheduleContract.MapMarkers.MARKER_ID, marker.id);
builder.withValue(ScheduleContract.MapMarkers.MARKER_FLOOR, floor);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LABEL,
marker.title);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LATITUDE,
marker.lat);
builder.withValue(ScheduleContract.MapMarkers.MARKER_LONGITUDE,
marker.lng);
builder.withValue(ScheduleContract.MapMarkers.MARKER_TYPE,
marker.type);
builder.withValue(ScheduleContract.MapMarkers.MARKER_TRACK, marker.track);
batch.add(builder.build());
}
}
}
private void parseTileOverlays(Map<String, Tile> tiles,
ArrayList<ContentProviderOperation> batch, Context context) {
for (Entry<String, Tile> entry : tiles.entrySet()) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(ScheduleContract.MapTiles.CONTENT_URI));
String floor = entry.getKey();
Tile value = entry.getValue();
builder.withValue(
ScheduleContract.MapTiles.TILE_FLOOR, floor);
builder.withValue(
ScheduleContract.MapTiles.TILE_FILE, value.filename);
builder.withValue(
ScheduleContract.MapTiles.TILE_URL, value.url);
Log.d(TAG, "adding overlay: " + floor + ", " + value.filename);
/*
* Setup the tile overlay file. Copy it from the app assets or
* download it if it does not exist locally. This is done here to
* ensure that the data stored in the content provider always points
* to valid tile files.
*/
batch.add(builder.build());
}
}
public Collection<Tile> getTiles(){
return mTiles;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.NetUtils;
import com.google.android.apps.iosched.util.UIUtils;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.plus.Plus;
import com.google.api.services.plus.model.Activity;
import com.google.api.services.plus.model.ActivityFeed;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class AnnouncementsFetcher {
private static final String TAG = makeLogTag(AnnouncementsFetcher.class);
private Context mContext;
public AnnouncementsFetcher(Context context) {
mContext = context;
}
public ArrayList<ContentProviderOperation> fetchAndParse() throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
// Set up the HTTP transport and JSON factory
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
// Set up the main Google+ class
Plus plus = new Plus.Builder(httpTransport, jsonFactory, null)
.setApplicationName(NetUtils.getUserAgent(mContext))
.setGoogleClientRequestInitializer(
new CommonGoogleClientRequestInitializer(Config.API_KEY))
.build();
ActivityFeed activities;
try {
activities = plus.activities().list(Config.ANNOUNCEMENTS_PLUS_ID, "public")
.setMaxResults(100l)
.execute();
if (activities == null || activities.getItems() == null) {
throw new IOException("Activities list was null.");
}
} catch (IOException e) {
LOGE(TAG, "Error fetching announcements", e);
return batch;
}
LOGI(TAG, "Updating announcements data");
// Clear out existing announcements
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Announcements.CONTENT_URI))
.build());
StringBuilder sb = new StringBuilder();
for (Activity activity : activities.getItems()) {
// Filter out anything not including the conference hashtag.
sb.setLength(0);
appendIfNotEmpty(sb, activity.getAnnotation());
if (activity.getObject() != null) {
appendIfNotEmpty(sb, activity.getObject().getContent());
}
if (!sb.toString().contains(UIUtils.CONFERENCE_HASHTAG)) {
continue;
}
// Insert announcement info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Announcements.ANNOUNCEMENT_ID, activity.getId())
.withValue(Announcements.ANNOUNCEMENT_DATE, activity.getUpdated().getValue())
.withValue(Announcements.ANNOUNCEMENT_TITLE, activity.getTitle())
.withValue(Announcements.ANNOUNCEMENT_ACTIVITY_JSON, activity.toPrettyString())
.withValue(Announcements.ANNOUNCEMENT_URL, activity.getUrl())
.build());
}
return batch;
}
private static void appendIfNotEmpty(StringBuilder sb, String s) {
if (!TextUtils.isEmpty(s)) {
sb.append(s);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import android.accounts.Account;
import android.content.ContentResolver;
import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.FeedbackColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkerColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.MapTileColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.AccountUtils;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Helper for managing {@link SQLiteDatabase} that stores data for
* {@link ScheduleProvider}.
*/
public class ScheduleDatabase extends SQLiteOpenHelper {
private static final String TAG = makeLogTag(ScheduleDatabase.class);
private static final String DATABASE_NAME = "schedule.db";
// NOTE: carefully update onUpgrade() when bumping database versions to make
// sure user data is saved.
private static final int VER_2013_LAUNCH = 104; // 1.0
private static final int VER_2013_RM2 = 105; // 1.1
private static final int DATABASE_VERSION = VER_2013_RM2;
private final Context mContext;
interface Tables {
String BLOCKS = "blocks";
String TRACKS = "tracks";
String ROOMS = "rooms";
String SESSIONS = "sessions";
String SPEAKERS = "speakers";
String SESSIONS_SPEAKERS = "sessions_speakers";
String SESSIONS_TRACKS = "sessions_tracks";
String SANDBOX = "sandbox";
String ANNOUNCEMENTS = "announcements";
String MAPMARKERS = "mapmarkers";
String MAPTILES = "mapoverlays";
String FEEDBACK = "feedback";
String SESSIONS_SEARCH = "sessions_search";
String SEARCH_SUGGEST = "search_suggest";
String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_ROOMS = "sessions "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS = "sandbox "
+ "LEFT OUTER JOIN tracks ON sandbox.track_id=tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sandbox.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sandbox.room_id=rooms.room_id";
String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers "
+ "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id";
String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers "
+ "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks "
+ "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id";
String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks "
+ "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search "
+ "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions "
+ "LEFT OUTER JOIN sessions_tracks ON "
+ "sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id";
String BLOCKS_JOIN_SESSIONS = "blocks "
+ "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id";
String MAPMARKERS_JOIN_TRACKS = "mapmarkers "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=mapmarkers.track_id ";
}
private interface Triggers {
// Deletes from session_tracks and sessions_speakers when corresponding sessions
// are deleted.
String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete";
String SESSIONS_SPEAKERS_DELETE = "sessions_speakers_delete";
String SESSIONS_FEEDBACK_DELETE = "sessions_feedback_delete";
}
public interface SessionsSpeakers {
String SESSION_ID = "session_id";
String SPEAKER_ID = "speaker_id";
}
public interface SessionsTracks {
String SESSION_ID = "session_id";
String TRACK_ID = "track_id";
}
interface SessionsSearchColumns {
String SESSION_ID = "session_id";
String BODY = "body";
}
/** Fully-qualified field names. */
private interface Qualified {
String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID
+ "," + SessionsSearchColumns.BODY + ")";
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS+ "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS+ "."
+ SessionsSpeakers.SPEAKER_ID;
String SPEAKERS_SPEAKER_ID = Tables.SPEAKERS + "." + Speakers.SPEAKER_ID;
String FEEDBACK_SESSION_ID = Tables.FEEDBACK + "." + FeedbackColumns.SESSION_ID;
}
/** {@code REFERENCES} clauses. */
private interface References {
String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")";
String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")";
String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")";
String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")";
String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")";
}
public ScheduleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.BLOCKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BlocksColumns.BLOCK_ID + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_START + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_END + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_TYPE + " TEXT,"
+ BlocksColumns.BLOCK_META + " TEXT,"
+ "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TracksColumns.TRACK_ID + " TEXT NOT NULL,"
+ TracksColumns.TRACK_NAME + " TEXT,"
+ TracksColumns.TRACK_COLOR + " INTEGER,"
+ TracksColumns.TRACK_LEVEL + " INTEGER,"
+ TracksColumns.TRACK_ORDER_IN_LEVEL + " INTEGER,"
+ TracksColumns.TRACK_META + " INTEGER NOT NULL DEFAULT 0,"
+ TracksColumns.TRACK_ABSTRACT + " TEXT,"
+ TracksColumns.TRACK_HASHTAG + " TEXT,"
+ "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ROOMS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ RoomsColumns.ROOM_ID + " TEXT NOT NULL,"
+ RoomsColumns.ROOM_NAME + " TEXT,"
+ RoomsColumns.ROOM_FLOOR + " TEXT,"
+ "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SessionsColumns.SESSION_ID + " TEXT NOT NULL,"
+ Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ SessionsColumns.SESSION_TYPE + " TEXT,"
+ SessionsColumns.SESSION_LEVEL + " TEXT,"
+ SessionsColumns.SESSION_TITLE + " TEXT,"
+ SessionsColumns.SESSION_ABSTRACT + " TEXT,"
+ SessionsColumns.SESSION_REQUIREMENTS + " TEXT,"
+ SessionsColumns.SESSION_TAGS + " TEXT,"
+ SessionsColumns.SESSION_HASHTAGS + " TEXT,"
+ SessionsColumns.SESSION_URL + " TEXT,"
+ SessionsColumns.SESSION_YOUTUBE_URL + " TEXT,"
+ SessionsColumns.SESSION_MODERATOR_URL + " TEXT,"
+ SessionsColumns.SESSION_PDF_URL + " TEXT,"
+ SessionsColumns.SESSION_NOTES_URL + " TEXT,"
+ SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0,"
+ SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER,"
+ SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT,"
+ "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL,"
+ SpeakersColumns.SPEAKER_NAME + " TEXT,"
+ SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT,"
+ SpeakersColumns.SPEAKER_COMPANY + " TEXT,"
+ SpeakersColumns.SPEAKER_ABSTRACT + " TEXT,"
+ SpeakersColumns.SPEAKER_URL + " TEXT,"
+ "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + ","
+ "UNIQUE (" + SessionsSpeakers.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID
+ ")");
db.execSQL("CREATE TABLE " + Tables.SANDBOX + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ ScheduleContract.SandboxColumns.COMPANY_ID + " TEXT NOT NULL,"
+ Sandbox.TRACK_ID + " TEXT " + References.TRACK_ID + ","
+ Sandbox.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sandbox.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ ScheduleContract.SandboxColumns.COMPANY_NAME + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_DESC + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_URL + " TEXT,"
+ ScheduleContract.SandboxColumns.COMPANY_LOGO_URL + " TEXT,"
+ "UNIQUE (" + ScheduleContract.SandboxColumns.COMPANY_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ACTIVITY_JSON + " BLOB,"
+ AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)");
db.execSQL("CREATE TABLE " + Tables.MAPTILES + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MapTileColumns.TILE_FLOOR+ " INTEGER NOT NULL,"
+ MapTileColumns.TILE_FILE+ " TEXT NOT NULL,"
+ MapTileColumns.TILE_URL+ " TEXT NOT NULL,"
+ "UNIQUE (" + MapTileColumns.TILE_FLOOR+ ") ON CONFLICT REPLACE)");
doMigration2013RM2(db);
// Full-text search index. Update using updateSessionSearchIndex method.
// Use the porter tokenizer for simple stemming, so that "frustration" matches "frustrated."
db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSearchColumns.BODY + " TEXT NOT NULL,"
+ SessionsSearchColumns.SESSION_ID
+ " TEXT NOT NULL " + References.SESSION_ID + ","
+ "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE,"
+ "tokenize=porter)");
// Search suggestions
db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)");
// Session deletion triggers
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " "
+ " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SPEAKERS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SPEAKERS + " "
+ " WHERE " + Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
}
private void doMigration2013RM2(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.FEEDBACK + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ Sessions.SESSION_ID + " TEXT " + References.SESSION_ID + ","
+ FeedbackColumns.SESSION_RATING + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_RELEVANCE + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_CONTENT + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_SPEAKER + " INTEGER NOT NULL,"
+ FeedbackColumns.ANSWER_WILLUSE + " INTEGER NOT NULL,"
+ FeedbackColumns.COMMENTS + " TEXT)");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_FEEDBACK_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.FEEDBACK + " "
+ " WHERE " + Qualified.FEEDBACK_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TABLE " + Tables.MAPMARKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ MapMarkerColumns.MARKER_ID+ " TEXT NOT NULL,"
+ MapMarkerColumns.MARKER_TYPE+ " TEXT NOT NULL,"
+ MapMarkerColumns.MARKER_LATITUDE+ " DOUBLE NOT NULL,"
+ MapMarkerColumns.MARKER_LONGITUDE+ " DOUBLE NOT NULL,"
+ MapMarkerColumns.MARKER_LABEL+ " TEXT,"
+ MapMarkerColumns.MARKER_FLOOR+ " INTEGER NOT NULL,"
+ MapMarkerColumns.MARKER_TRACK+ " TEXT,"
+ "UNIQUE (" + MapMarkerColumns.MARKER_ID + ") ON CONFLICT REPLACE)");
}
/**
* Updates the session search index. This should be done sparingly, as the queries are rather
* complex.
*/
static void updateSessionSearchIndex(SQLiteDatabase db) {
db.execSQL("DELETE FROM " + Tables.SESSIONS_SEARCH);
db.execSQL("INSERT INTO " + Qualified.SESSIONS_SEARCH
+ " SELECT s." + Sessions.SESSION_ID + ",("
// Full text body
+ Sessions.SESSION_TITLE + "||'; '||"
+ Sessions.SESSION_ABSTRACT + "||'; '||"
+ "IFNULL(" + Sessions.SESSION_TAGS + ",'')||'; '||"
+ "IFNULL(GROUP_CONCAT(t." + Speakers.SPEAKER_NAME + ",' '),'')||'; '||"
+ "'')"
+ " FROM " + Tables.SESSIONS + " s "
+ " LEFT OUTER JOIN"
// Subquery resulting in session_id, speaker_id, speaker_name
+ "(SELECT " + Sessions.SESSION_ID + "," + Qualified.SPEAKERS_SPEAKER_ID
+ "," + Speakers.SPEAKER_NAME
+ " FROM " + Tables.SESSIONS_SPEAKERS
+ " INNER JOIN " + Tables.SPEAKERS
+ " ON " + Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "="
+ Qualified.SPEAKERS_SPEAKER_ID
+ ") t"
// Grand finale
+ " ON s." + Sessions.SESSION_ID + "=t." + Sessions.SESSION_ID
+ " GROUP BY s." + Sessions.SESSION_ID);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
// Cancel any sync currently in progress
Account account = AccountUtils.getChosenAccount(mContext);
if (account != null) {
LOGI(TAG, "Cancelling any pending syncs for for account");
ContentResolver.cancelSync(account, ScheduleContract.CONTENT_AUTHORITY);
}
// NOTE: This switch statement is designed to handle cascading database
// updates, starting at the current version and falling through to all
// future upgrade cases. Only use "break;" when you want to drop and
// recreate the entire database.
int version = oldVersion;
switch (version) {
// Note: Data from prior years not preserved.
case VER_2013_LAUNCH:
LOGI(TAG, "Performing migration for DB version " + version);
// Reset BLOCKS table
db.execSQL("DELETE FROM " + Tables.BLOCKS);
// Reset MapMarkers table
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS);
// Apply new schema changes
doMigration2013RM2(db);
case VER_2013_RM2:
version = VER_2013_RM2;
LOGI(TAG, "DB at version " + version);
// Current version, no further action necessary
}
LOGD(TAG, "after upgrade logic, at version " + version);
if (version != DATABASE_VERSION) {
LOGW(TAG, "Destroying old data during upgrade");
db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SANDBOX);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.FEEDBACK);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SPEAKERS_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_FEEDBACK_DELETE);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST);
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPMARKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.MAPTILES);
onCreate(db);
}
if (account != null) {
LOGI(TAG, "DB upgrade complete. Requesting resync.");
SyncHelper.requestManualSync(account);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.appwidget.ScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Feedback;
import com.google.android.apps.iosched.provider.ScheduleContract.MapMarkers;
import com.google.android.apps.iosched.provider.ScheduleContract.MapTiles;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.Sandbox;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables;
import com.google.android.apps.iosched.util.SelectionBuilder;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.text.TextUtils;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various
* {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = makeLogTag(ScheduleProvider.class);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int BLOCKS_ID_SESSIONS_STARRED = 104;
private static final int TRACKS = 200;
private static final int TRACKS_ID = 201;
private static final int TRACKS_ID_SESSIONS = 202;
private static final int TRACKS_ID_SANDBOX = 203;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_WITH_TRACK = 402;
private static final int SESSIONS_SEARCH = 403;
private static final int SESSIONS_AT = 404;
private static final int SESSIONS_ID = 405;
private static final int SESSIONS_ID_SPEAKERS = 406;
private static final int SESSIONS_ID_TRACKS = 407;
private static final int SESSIONS_ID_WITH_TRACK = 408;
private static final int SESSIONS_ROOM_AFTER = 410;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_ID_SESSIONS = 502;
private static final int SANDBOX = 600;
private static final int SANDBOX_SEARCH = 603;
private static final int SANDBOX_ID = 604;
private static final int ANNOUNCEMENTS = 700;
private static final int ANNOUNCEMENTS_ID = 701;
private static final int SEARCH_SUGGEST = 800;
private static final int SEARCH_INDEX = 801;
private static final int MAPMARKERS = 900;
private static final int MAPMARKERS_FLOOR = 901;
private static final int MAPMARKERS_ID = 902;
private static final int MAPTILES = 1000;
private static final int MAPTILES_FLOOR = 1001;
private static final int FEEDBACK_ALL = 1002;
private static final int FEEDBACK_FOR_SESSION = 1003;
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED);
matcher.addURI(authority, "tracks", TRACKS);
matcher.addURI(authority, "tracks/*", TRACKS_ID);
matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS);
matcher.addURI(authority, "tracks/*/sandbox", TRACKS_ID_SANDBOX);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/room/*/after/*", SESSIONS_ROOM_AFTER);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS);
matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS);
matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS);
matcher.addURI(authority, "sandbox", SANDBOX);
matcher.addURI(authority, "sandbox/search/*", SANDBOX_SEARCH);
matcher.addURI(authority, "sandbox/*", SANDBOX_ID);
matcher.addURI(authority, "announcements", ANNOUNCEMENTS);
matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
matcher.addURI(authority, "search_index", SEARCH_INDEX); // 'update' only
matcher.addURI(authority, "mapmarkers", MAPMARKERS);
matcher.addURI(authority, "mapmarkers/floor/*", MAPMARKERS_FLOOR);
matcher.addURI(authority, "mapmarkers/*", MAPMARKERS_ID);
matcher.addURI(authority, "maptiles", MAPTILES);
matcher.addURI(authority, "maptiles/*", MAPTILES_FLOOR);
matcher.addURI(authority, "feedback/*", FEEDBACK_FOR_SESSION);
matcher.addURI(authority, "feedback*", FEEDBACK_ALL);
matcher.addURI(authority, "feedback", FEEDBACK_ALL);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new ScheduleDatabase(getContext());
return true;
}
private void deleteDatabase() {
// TODO: wait for content provider operations to finish, then tear down
mOpenHelper.close();
Context context = getContext();
ScheduleDatabase.deleteDatabase(context);
mOpenHelper = new ScheduleDatabase(getContext());
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case BLOCKS_ID_SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case TRACKS:
return Tracks.CONTENT_TYPE;
case TRACKS_ID:
return Tracks.CONTENT_ITEM_TYPE;
case TRACKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TRACKS_ID_SANDBOX:
return Sandbox.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SESSIONS_ID_SPEAKERS:
return Speakers.CONTENT_TYPE;
case SESSIONS_ID_TRACKS:
return Tracks.CONTENT_TYPE;
case SESSIONS_ID_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_ROOM_AFTER:
return Sessions.CONTENT_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SANDBOX:
return Sandbox.CONTENT_TYPE;
case SANDBOX_SEARCH:
return ScheduleContract.Sandbox.CONTENT_TYPE;
case SANDBOX_ID:
return ScheduleContract.Sandbox.CONTENT_ITEM_TYPE;
case ANNOUNCEMENTS:
return Announcements.CONTENT_TYPE;
case ANNOUNCEMENTS_ID:
return Announcements.CONTENT_ITEM_TYPE;
case MAPMARKERS:
return MapMarkers.CONTENT_TYPE;
case MAPMARKERS_FLOOR:
return MapMarkers.CONTENT_TYPE;
case MAPMARKERS_ID:
return MapMarkers.CONTENT_ITEM_TYPE;
case MAPTILES:
return MapTiles.CONTENT_TYPE;
case MAPTILES_FLOOR:
return MapTiles.CONTENT_ITEM_TYPE;
case FEEDBACK_FOR_SESSION:
return Feedback.CONTENT_ITEM_TYPE;
case FEEDBACK_ALL:
return Feedback.CONTENT_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
String uriFilter = uri.getQueryParameter(Sessions.QUERY_PARAMETER_FILTER);
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
// If a special filter was specified, try to apply it
if (!TextUtils.isEmpty(uriFilter)) {
if (Sessions.QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY.equals(uriFilter)) {
builder.where(Sessions.SESSION_TYPE + " NOT IN ('"
+ Sessions.SESSION_TYPE_OFFICE_HOURS + "','"
+ Sessions.SESSION_TYPE_KEYNOTE + "')");
} else if (Sessions.QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY.equals(uriFilter)) {
builder.where(Sessions.SESSION_TYPE + " = ?",
Sessions.SESSION_TYPE_OFFICE_HOURS);
}
}
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
case SEARCH_SUGGEST: {
final SelectionBuilder builder = new SelectionBuilder();
// Adjust incoming query to become SQL text match
selectionArgs[0] = selectionArgs[0] + "%";
builder.table(Tables.SEARCH_SUGGEST);
builder.where(selection, selectionArgs);
builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_TEXT_1);
projection = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_QUERY
};
final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
}
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
notifyChange(uri, syncToNetwork);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TRACKS: {
db.insertOrThrow(Tables.TRACKS, null, values);
notifyChange(uri, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
notifyChange(uri, syncToNetwork);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
notifyChange(uri, syncToNetwork);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SESSIONS_ID_SPEAKERS: {
db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values);
notifyChange(uri, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID));
}
case SESSIONS_ID_TRACKS: {
db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values);
notifyChange(uri, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
notifyChange(uri, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
case SANDBOX: {
db.insertOrThrow(Tables.SANDBOX, null, values);
notifyChange(uri, syncToNetwork);
return Sandbox.buildCompanyUri(values.getAsString(Sandbox.COMPANY_ID));
}
case ANNOUNCEMENTS: {
db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values);
notifyChange(uri, syncToNetwork);
return Announcements.buildAnnouncementUri(values
.getAsString(Announcements.ANNOUNCEMENT_ID));
}
case SEARCH_SUGGEST: {
db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values);
notifyChange(uri, syncToNetwork);
return SearchSuggest.CONTENT_URI;
}
case MAPMARKERS: {
db.insertOrThrow(Tables.MAPMARKERS, null, values);
notifyChange(uri, syncToNetwork);
return MapMarkers.buildMarkerUri(values.getAsString(MapMarkers.MARKER_ID));
}
case MAPTILES: {
db.insertOrThrow(Tables.MAPTILES, null, values);
notifyChange(uri, syncToNetwork);
return MapTiles.buildFloorUri(values.getAsString(MapTiles.TILE_FLOOR));
}
case FEEDBACK_FOR_SESSION: {
db.insertOrThrow(Tables.FEEDBACK, null, values);
notifyChange(uri, syncToNetwork);
return Feedback.buildFeedbackUri(values.getAsString(Feedback.SESSION_ID));
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
if (match == SEARCH_INDEX) {
// update the search index
ScheduleDatabase.updateSessionSearchIndex(db);
return 1;
}
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
notifyChange(uri, syncToNetwork);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
LOGV(TAG, "delete(uri=" + uri + ")");
if (uri == ScheduleContract.BASE_CONTENT_URI) {
// Handle whole database deletes (e.g. when signing out)
deleteDatabase();
notifyChange(uri, false);
return 1;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
notifyChange(uri, !ScheduleContract.hasCallerIsSyncAdapterParameter(uri));
return retVal;
}
private void notifyChange(Uri uri, boolean syncToNetwork) {
Context context = getContext();
context.getContentResolver().notifyChange(uri, null, syncToNetwork);
// Widgets can't register content observers so we refresh widgets separately.
context.sendBroadcast(ScheduleWidgetProvider.getRefreshBroadcastIntent(context, false));
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TRACKS: {
return builder.table(Tables.TRACKS);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SANDBOX: {
return builder.table(Tables.SANDBOX);
}
case SANDBOX_ID: {
final String companyId = ScheduleContract.Sandbox.getCompanyId(uri);
return builder.table(Tables.SANDBOX)
.where(Sandbox.COMPANY_ID + "=?", companyId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case MAPMARKERS: {
return builder.table(Tables.MAPMARKERS);
}
case MAPMARKERS_FLOOR: {
final String floor = MapMarkers.getMarkerFloor(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_FLOOR+ "=?", floor);
}
case MAPMARKERS_ID: {
final String markerId = MapMarkers.getMarkerId(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_ID+ "=?", markerId);
}
case MAPTILES: {
return builder.table(Tables.MAPTILES);
}
case MAPTILES_FLOOR: {
final String floor = MapTiles.getFloorId(uri);
return builder.table(Tables.MAPTILES)
.where(MapTiles.TILE_FLOOR+ "=?", floor);
}
case SEARCH_SUGGEST: {
return builder.table(Tables.SEARCH_SUGGEST);
}
case FEEDBACK_FOR_SESSION: {
final String session_id = Feedback.getSessionId(uri);
return builder.table(Tables.FEEDBACK)
.where(Feedback.SESSION_ID + "=?", session_id);
}
case FEEDBACK_ALL: {
return builder.table(Tables.FEEDBACK);
}
default: {
throw new UnsupportedOperationException("Unknown uri for " + match + ": " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder
.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID)
.map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE)
.map(Blocks.STARRED_SESSION_HASHTAGS,
Subquery.BLOCK_STARRED_SESSION_HASHTAGS)
.map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL)
.map(Blocks.STARRED_SESSION_LIVESTREAM_URL,
Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL)
.map(Blocks.STARRED_SESSION_ROOM_NAME,
Subquery.BLOCK_STARRED_SESSION_ROOM_NAME)
.map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS_STARRED: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.NUM_LIVESTREAMED_SESSIONS,
Subquery.BLOCK_NUM_LIVESTREAMED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId)
.where(Qualified.SESSIONS_STARRED + "=1");
}
case TRACKS: {
return builder.table(Tables.TRACKS)
.map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT)
.map(Tracks.OFFICE_HOURS_COUNT, Subquery.TRACK_OFFICE_HOURS_COUNT)
.map(Tracks.SANDBOX_COUNT, Subquery.TRACK_SANDBOX_COUNT);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SESSIONS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SANDBOX: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(ScheduleContract.Sandbox.BLOCK_ID, Tables.BLOCKS)
.mapToTable(Sandbox.ROOM_ID, Tables.ROOMS)
.where(Qualified.SANDBOX_TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_WITH_TRACK: {
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS);
}
case SESSIONS_ID_WITH_TRACK: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS)
.mapToTable(Speakers._ID, Tables.SPEAKERS)
.mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS)
.where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS)
.mapToTable(Tracks._ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ROOM_AFTER: {
final String room = Sessions.getRoom(uri);
final String time = Sessions.getAfter(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID+ "=?", room)
.where("("+Sessions.BLOCK_START + "<= ? AND "+Sessions.BLOCK_END+">= ?) OR ("+Sessions.BLOCK_START+" >= ?)", time,time,time);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_ID_SESSIONS: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId);
}
case SANDBOX: {
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX);
}
case SANDBOX_ID: {
final String companyId = ScheduleContract.Sandbox.getCompanyId(uri);
return builder.table(Tables.SANDBOX_JOIN_TRACKS_BLOCKS_ROOMS)
.mapToTable(ScheduleContract.Sandbox._ID, Tables.SANDBOX)
.mapToTable(Sandbox.TRACK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.BLOCK_ID, Tables.SANDBOX)
.mapToTable(Sandbox.ROOM_ID, Tables.SANDBOX)
.where(Sandbox.COMPANY_ID + "=?", companyId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case MAPMARKERS: {
return builder.table(Tables.MAPMARKERS);
}
case MAPMARKERS_FLOOR: {
final String floor = MapMarkers.getMarkerFloor(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_FLOOR+ "=?", floor);
}
case MAPMARKERS_ID: {
final String roomId = MapMarkers.getMarkerId(uri);
return builder.table(Tables.MAPMARKERS)
.where(MapMarkers.MARKER_ID+ "=?", roomId);
}
case MAPTILES: {
return builder.table(Tables.MAPTILES);
}
case MAPTILES_FLOOR: {
final String floor = MapTiles.getFloorId(uri);
return builder.table(Tables.MAPTILES)
.where(MapTiles.TILE_FLOOR+ "=?", floor);
}
case FEEDBACK_FOR_SESSION: {
final String sessionId = Feedback.getSessionId(uri);
return builder.table(Tables.FEEDBACK)
.where(Feedback.SESSION_ID + "=?", sessionId);
}
case FEEDBACK_ALL: {
return builder.table(Tables.FEEDBACK);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_NUM_LIVESTREAMED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID
+ " AND IFNULL(" + Qualified.SESSIONS_LIVESTREAM_URL + ",'')!='')";
String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT "
+ Qualified.SESSIONS_LIVESTREAM_URL
+ " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON "
+ Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID
+ " AND " + Qualified.SESSIONS_SESSION_TYPE + " != \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")";
String TRACK_OFFICE_HOURS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " INNER JOIN " + Tables.SESSIONS + " ON "
+ Qualified.SESSIONS_SESSION_ID + "=" + Qualified.SESSIONS_TRACKS_SESSION_ID + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID
+ " AND " + Qualified.SESSIONS_SESSION_TYPE + " = \"" + Sessions.SESSION_TYPE_OFFICE_HOURS + "\")";
String TRACK_SANDBOX_COUNT = "(SELECT COUNT(" + Qualified.SANDBOX_COMPANY_ID + ") FROM "
+ Tables.SANDBOX + " WHERE " + Qualified.SANDBOX_TRACK_ID + "="
+ Qualified.TRACKS_TRACK_ID + ")";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_SESSION_TYPE = Tables.SESSIONS+ "." + Sessions.SESSION_TYPE;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.TRACK_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SPEAKER_ID;
String SANDBOX_COMPANY_ID = Tables.SANDBOX + "." + Sandbox.COMPANY_ID;
String SANDBOX_TRACK_ID = Tables.SANDBOX + "." + Sandbox.TRACK_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS;
String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL;
String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL;
String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME;
String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID;
String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.util.ParserUtils;
import android.app.SearchManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.util.List;
/**
* Contract class for interacting with {@link ScheduleProvider}. Unless
* otherwise noted, all time-based fields are milliseconds since epoch and can
* be compared against {@link System#currentTimeMillis()}.
* <p>
* The backing {@link android.content.ContentProvider} assumes that {@link Uri}
* are generated using stronger {@link String} identifiers, instead of
* {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during
* sync.
*/
public class ScheduleContract {
/**
* Special value for {@link SyncColumns#UPDATED} indicating that an entry
* has never been updated, or doesn't exist yet.
*/
public static final long UPDATED_NEVER = -2;
/**
* Special value for {@link SyncColumns#UPDATED} indicating that the last
* update time is unknown, usually when inserted from a local file source.
*/
public static final long UPDATED_UNKNOWN = -1;
public interface SyncColumns {
/** Last time this entry was updated or synchronized. */
String UPDATED = "updated";
}
interface BlocksColumns {
/** Unique string identifying this block of time. */
String BLOCK_ID = "block_id";
/** Title describing this block of time. */
String BLOCK_TITLE = "block_title";
/** Time when this block starts. */
String BLOCK_START = "block_start";
/** Time when this block ends. */
String BLOCK_END = "block_end";
/** Type describing this block. */
String BLOCK_TYPE = "block_type";
/** Extra string metadata for the block. */
String BLOCK_META = "block_meta";
}
interface TracksColumns {
/** Unique string identifying this track. */
String TRACK_ID = "track_id";
/** Name describing this track. */
String TRACK_NAME = "track_name";
/** Color used to identify this track, in {@link Color#argb} format. */
String TRACK_COLOR = "track_color";
/** The level (1 being primary, 2 being secondary) of the track. */
String TRACK_LEVEL = "track_level";
/** The sort order of the track within the level. */
String TRACK_ORDER_IN_LEVEL = "track_order_in_level";
/** Type of meta-track this is, or 0 if not meta. */
String TRACK_META = "track_is_meta";
/** Type of track. */
String TRACK_ABSTRACT = "track_abstract";
/** Hashtag for track. */
String TRACK_HASHTAG = "track_hashtag";
}
interface RoomsColumns {
/** Unique string identifying this room. */
String ROOM_ID = "room_id";
/** Name describing this room. */
String ROOM_NAME = "room_name";
/** Building floor this room exists on. */
String ROOM_FLOOR = "room_floor";
}
interface SessionsColumns {
/** Unique string identifying this session. */
String SESSION_ID = "session_id";
/** The type of session (session, keynote, codelab, etc). */
String SESSION_TYPE = "session_type";
/** Difficulty level of the session. */
String SESSION_LEVEL = "session_level";
/** Title describing this track. */
String SESSION_TITLE = "session_title";
/** Body of text explaining this session in detail. */
String SESSION_ABSTRACT = "session_abstract";
/** Requirements that attendees should meet. */
String SESSION_REQUIREMENTS = "session_requirements";
/** Kewords/tags for this session. */
String SESSION_TAGS = "session_keywords";
/** Hashtag for this session. */
String SESSION_HASHTAGS = "session_hashtag";
/** Full URL to session online. */
String SESSION_URL = "session_url";
/** Full URL to YouTube. */
String SESSION_YOUTUBE_URL = "session_youtube_url";
/** Full URL to PDF. */
String SESSION_PDF_URL = "session_pdf_url";
/** Full URL to official session notes. */
String SESSION_NOTES_URL = "session_notes_url";
/** User-specific flag indicating starred status. */
String SESSION_STARRED = "session_starred";
/** Key for session Calendar event. (Used in ICS or above) */
String SESSION_CAL_EVENT_ID = "session_cal_event_id";
/** The YouTube live stream URL. */
String SESSION_LIVESTREAM_URL = "session_livestream_url";
/** The Moderator URL. */
String SESSION_MODERATOR_URL = "session_moderator_url";
}
interface SpeakersColumns {
/** Unique string identifying this speaker. */
String SPEAKER_ID = "speaker_id";
/** Name of this speaker. */
String SPEAKER_NAME = "speaker_name";
/** Profile photo of this speaker. */
String SPEAKER_IMAGE_URL = "speaker_image_url";
/** Company this speaker works for. */
String SPEAKER_COMPANY = "speaker_company";
/** Body of text describing this speaker in detail. */
String SPEAKER_ABSTRACT = "speaker_abstract";
/** Full URL to the speaker's profile. */
String SPEAKER_URL = "speaker_url";
}
interface SandboxColumns {
/** Unique string identifying this sandbox company. */
String COMPANY_ID = "company_id";
/** Name of this sandbox company. */
String COMPANY_NAME = "company_name";
/** Body of text describing this sandbox company. */
String COMPANY_DESC = "company_desc";
/** Link to sandbox company online. */
String COMPANY_URL = "company_url";
/** Link to sandbox company logo. */
String COMPANY_LOGO_URL = "company_logo_url";
}
interface AnnouncementsColumns {
/** Unique string identifying this announcment. */
String ANNOUNCEMENT_ID = "announcement_id";
/** Title of the announcement. */
String ANNOUNCEMENT_TITLE = "announcement_title";
/** Google+ activity JSON for the announcement. */
String ANNOUNCEMENT_ACTIVITY_JSON = "announcement_activity_json";
/** Full URL for the announcement. */
String ANNOUNCEMENT_URL = "announcement_url";
/** Date of the announcement. */
String ANNOUNCEMENT_DATE = "announcement_date";
}
interface MapMarkerColumns {
/** Unique string identifying this marker. */
String MARKER_ID = "map_marker_id";
/** Type of marker. */
String MARKER_TYPE = "map_marker_type";
/** Latitudinal position of marker. */
String MARKER_LATITUDE = "map_marker_latitude";
/** Longitudinal position of marker. */
String MARKER_LONGITUDE = "map_marker_longitude";
/** Label (title) for this marker. */
String MARKER_LABEL = "map_marker_label";
/** Building floor this marker is on. */
String MARKER_FLOOR = "map_marker_floor";
/** Track of sandbox marker */
String MARKER_TRACK = "track_id";
}
interface FeedbackColumns {
String SESSION_ID = "session_id";
String SESSION_RATING = "feedback_session_rating";
String ANSWER_RELEVANCE = "feedback_answer_q1";
String ANSWER_CONTENT = "feedback_answer_q2";
String ANSWER_SPEAKER = "feedback_answer_q3";
String ANSWER_WILLUSE = "feedback_answer_q4";
String COMMENTS = "feedback_comments";
}
interface MapTileColumns {
/** Floor **/
String TILE_FLOOR = "map_tile_floor";
/** Filename **/
String TILE_FILE = "map_tile_file";
/** Url **/
String TILE_URL = "map_tile_url";
}
public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_BLOCKS = "blocks";
private static final String PATH_AT = "at";
private static final String PATH_AFTER = "after";
private static final String PATH_BETWEEN = "between";
private static final String PATH_TRACKS = "tracks";
private static final String PATH_ROOM = "room";
private static final String PATH_ROOMS = "rooms";
private static final String PATH_SESSIONS = "sessions";
private static final String PATH_FEEDBACK = "feedback";
private static final String PATH_WITH_TRACK = "with_track";
private static final String PATH_STARRED = "starred";
private static final String PATH_SPEAKERS = "speakers";
private static final String PATH_SANDBOX = "sandbox";
private static final String PATH_ANNOUNCEMENTS = "announcements";
private static final String PATH_MAP_MARKERS = "mapmarkers";
private static final String PATH_MAP_FLOOR = "floor";
private static final String PATH_MAP_TILES= "maptiles";
private static final String PATH_SEARCH = "search";
private static final String PATH_SEARCH_SUGGEST = "search_suggest_query";
private static final String PATH_SEARCH_INDEX = "search_index";
/**
* Blocks are generic timeslots that {@link Sessions} and other related
* events fall into.
*/
public static class Blocks implements BlocksColumns, BaseColumns {
public static final String BLOCK_TYPE_GENERIC = "generic";
public static final String BLOCK_TYPE_FOOD = "food";
public static final String BLOCK_TYPE_SESSION = "session";
public static final String BLOCK_TYPE_CODELAB = "codelab";
public static final String BLOCK_TYPE_KEYNOTE = "keynote";
public static final String BLOCK_TYPE_OFFICE_HOURS = "officehours";
public static final String BLOCK_TYPE_SANDBOX = "sandbox_only";
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.block";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.block";
/** Count of {@link Sessions} inside given block. */
public static final String SESSIONS_COUNT = "sessions_count";
/**
* Flag indicating the number of sessions inside this block that have
* {@link Sessions#SESSION_STARRED} set.
*/
public static final String NUM_STARRED_SESSIONS = "num_starred_sessions";
/**
* Flag indicating the number of sessions inside this block that have a
* {@link Sessions#SESSION_LIVESTREAM_URL} set.
*/
public static final String NUM_LIVESTREAMED_SESSIONS = "num_livestreamed_sessions";
/**
* The {@link Sessions#SESSION_ID} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ID = "starred_session_id";
/**
* The {@link Sessions#SESSION_TITLE} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_TITLE = "starred_session_title";
/**
* The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred
* session in this block.
*/
public static final String STARRED_SESSION_LIVESTREAM_URL =
"starred_session_livestream_url";
/**
* The {@link Rooms#ROOM_NAME} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name";
/**
* The {@link Rooms#ROOM_ID} of the first starred session in this block.
*/
public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id";
/**
* The {@link Sessions#SESSION_HASHTAGS} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags";
/**
* The {@link Sessions#SESSION_URL} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_URL = "starred_session_url";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, "
+ BlocksColumns.BLOCK_END + " ASC";
public static final String EMPTY_SESSIONS_SELECTION = BLOCK_TYPE + " IN ('"
+ Blocks.BLOCK_TYPE_SESSION + "','"
+ Blocks.BLOCK_TYPE_CODELAB + "','"
+ Blocks.BLOCK_TYPE_OFFICE_HOURS + "') AND "
+ SESSIONS_COUNT + " = 0";
/** Build {@link Uri} for requested {@link #BLOCK_ID}. */
public static Uri buildBlockUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references starred {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildStarredSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)
.appendPath(PATH_STARRED).build();
}
/** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */
public static String getBlockId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #BLOCK_ID} that will always match the requested
* {@link Blocks} details.
*/
public static String generateBlockId(long startTime, long endTime) {
startTime /= DateUtils.SECOND_IN_MILLIS;
endTime /= DateUtils.SECOND_IN_MILLIS;
return ParserUtils.sanitizeId(startTime + "-" + endTime);
}
}
/**
* Tracks are overall categories for {@link Sessions} and {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox},
* such as "Android" or "Enterprise."
*/
public static class Tracks implements TracksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();
public static final int TRACK_META_NONE = 0;
public static final int TRACK_META_SESSIONS_ONLY = 1;
public static final int TRACK_META_SANDBOX_OFFICE_HOURS_ONLY = 2;
public static final int TRACK_META_OFFICE_HOURS_ONLY = 3;
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.track";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.track";
/** "All tracks" ID. */
public static final String ALL_TRACK_ID = "all";
/** Count of {@link Sessions} inside given track that aren't office hours. */
public static final String SESSIONS_COUNT = "sessions_count";
/** Count of {@link Sessions} inside given track that are office hours. */
public static final String OFFICE_HOURS_COUNT = "office_hours_count";
/** Count of {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} inside given track. */
public static final String SANDBOX_COUNT = "sandbox_count";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = TracksColumns.TRACK_LEVEL + ", "
+ TracksColumns.TRACK_ORDER_IN_LEVEL + ", "
+ TracksColumns.TRACK_NAME;
/** Build {@link Uri} for requested {@link #TRACK_ID}. */
public static Uri buildTrackUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #TRACK_ID}.
*/
public static Uri buildSessionsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references any {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} associated with
* the requested {@link #TRACK_ID}.
*/
public static Uri buildSandboxUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SANDBOX).build();
}
/** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */
public static String getTrackId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Rooms are physical locations at the conference venue.
*/
public static class Rooms implements RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.room";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.room";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, "
+ RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ROOM_ID}. */
public static Uri buildRoomUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #ROOM_ID}.
*/
public static Uri buildSessionsDirUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */
public static String getRoomId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each session is a block of time that has a {@link Tracks}, a
* {@link Rooms}, and zero or more {@link Speakers}.
*/
public static class Feedback implements BaseColumns, FeedbackColumns, SyncColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_FEEDBACK).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session_feedback";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session_feedback";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BaseColumns._ID + " ASC, ";
/** Build {@link Uri} to feedback for given session. */
public static Uri buildFeedbackUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/** Read {@link #SESSION_ID} from {@link Feedback} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,
SyncColumns, BaseColumns {
public static final String SESSION_TYPE_SESSION = "SESSION";
public static final String SESSION_TYPE_CODELAB = "CODE_LAB";
public static final String SESSION_TYPE_KEYNOTE = "KEYNOTE";
public static final String SESSION_TYPE_OFFICE_HOURS = "OFFICE_HOURS";
public static final String SESSION_TYPE_SANDBOX = "DEVELOPER_SANDBOX";
public static final String QUERY_PARAMETER_FILTER = "filter";
public static final String QUERY_VALUE_FILTER_SESSIONS_CODELABS_ONLY
= "sessions_codelabs_only"; // excludes keynote and office hours
public static final String QUERY_VALUE_FILTER_OFFICE_HOURS_ONLY = "office_hours_only";
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();
public static final Uri CONTENT_STARRED_URI =
CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session";
public static final String BLOCK_ID = "block_id";
public static final String ROOM_ID = "room_id";
public static final String SEARCH_SNIPPET = "search_snippet";
// TODO: shortcut primary track to offer sub-sorting here
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC,"
+ SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC";
public static final String LIVESTREAM_SELECTION =
SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''";
// Used to fetch sessions for a particular time
public static final String AT_TIME_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeSelectionArgs(long time) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString };
}
// Used to fetch upcoming sessions
public static final String UPCOMING_SELECTION =
BLOCK_START + " = (select min(" + BLOCK_START + ") from " +
ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION +
" and " + BLOCK_START + " >" + " ?)";
// Builds selectionArgs for {@link UPCOMING_SELECTION}
public static String[] buildUpcomingSelectionArgs(long minTime) {
return new String[] { String.valueOf(minTime) };
}
/** Build {@link Uri} for requested {@link #SESSION_ID}. */
public static Uri buildSessionUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/**
* Build {@link Uri} that references any {@link Speakers} associated
* with the requested {@link #SESSION_ID}.
*/
public static Uri buildSpeakersDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();
}
/**
* Build {@link Uri} that includes track detail with list of sessions.
*/
public static Uri buildWithTracksUri() {
return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that includes track detail for a specific session.
*/
public static Uri buildWithTracksUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId)
.appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that references any {@link Tracks} associated with
* the requested {@link #SESSION_ID}.
*/
public static Uri buildTracksDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Build {@link Uri} that references sessions in a room that have begun after the requested time **/
public static Uri buildSessionsInRoomAfterUri(String room,long time) {
return CONTENT_URI.buildUpon().appendPath(PATH_ROOM).appendPath(room).appendPath(PATH_AFTER)
.appendPath(String.valueOf(time)).build();
}
public static String getRoom(Uri uri){
return uri.getPathSegments().get(2);
}
public static String getAfter(Uri uri){
return uri.getPathSegments().get(4);
}
/** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
}
/**
* Speakers are individual people that lead {@link Sessions}.
*/
public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.speaker";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.speaker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #SPEAKER_ID}. */
public static Uri buildSpeakerUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #SPEAKER_ID}.
*/
public static Uri buildSessionsDirUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */
public static String getSpeakerId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each sandbox company is a company appearing at the conference that may be
* associated with a specific {@link Tracks} and time block.
*/
public static class Sandbox implements SandboxColumns, SyncColumns, BlocksColumns, RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SANDBOX).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.sandbox";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.sandbox";
/** {@link Tracks#TRACK_ID} that this sandbox company belongs to. */
public static final String TRACK_ID = "track_id";
// Used to fetch sandbox companies at a particular time
public static final String AT_TIME_IN_ROOM_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ? and " + " SANDBOX.ROOM_ID = ?";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SandboxColumns.COMPANY_NAME
+ " COLLATE NOCASE ASC";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeInRoomSelectionArgs(long time, String roomId) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString, roomId };
}
/** Build {@link Uri} for requested {@link #COMPANY_ID}. */
public static Uri buildCompanyUri(String companyId) {
return CONTENT_URI.buildUpon().appendPath(companyId).build();
}
/** Read {@link #COMPANY_ID} from {@link com.google.android.apps.iosched.provider.ScheduleContract.Sandbox} {@link Uri}. */
public static String getCompanyId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Announcements of breaking news
*/
public static class Announcements implements AnnouncementsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.announcement";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.announcement";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE
+ " COLLATE NOCASE DESC";
/** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */
public static Uri buildAnnouncementUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId).build();
}
/**
* Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.
*/
public static String getAnnouncementId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* TileProvider entries are used to create an overlay provider for the map.
*/
public static class MapTiles implements MapTileColumns, BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_MAP_TILES).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.maptiles";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.maptiles";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = MapTileColumns.TILE_FLOOR + " ASC";
/** Build {@link Uri} for all overlay zoom entries */
public static Uri buildUri() {
return CONTENT_URI;
}
/** Build {@link Uri} for requested floor. */
public static Uri buildFloorUri(String floor) {
return CONTENT_URI.buildUpon()
.appendPath(String.valueOf(floor)).build();
}
/** Read floor from {@link MapMarkers} {@link Uri}. */
public static String getFloorId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Markers refer to marked positions on the map.
*/
public static class MapMarkers implements MapMarkerColumns, BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon()
.appendPath(PATH_MAP_MARKERS).build();
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.iosched.mapmarker";
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.iosched.mapmarker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = MapMarkerColumns.MARKER_FLOOR
+ " ASC, " + MapMarkerColumns.MARKER_ID + " ASC";
/** Build {@link Uri} for requested {@link #MARKER_ID}. */
public static Uri buildMarkerUri(String markerId) {
return CONTENT_URI.buildUpon().appendPath(markerId).build();
}
/** Build {@link Uri} for all markers */
public static Uri buildMarkerUri() {
return CONTENT_URI;
}
/** Build {@link Uri} for requested {@link #MARKER_ID}. */
public static Uri buildFloorUri(int floor) {
return CONTENT_URI.buildUpon().appendPath(PATH_MAP_FLOOR)
.appendPath("" + floor).build();
}
/** Read {@link #MARKER_ID} from {@link MapMarkers} {@link Uri}. */
public static String getMarkerId(Uri uri) {
return uri.getPathSegments().get(1);
}
/** Read {@link #FLOOR} from {@link MapMarkers} {@link Uri}. */
public static String getMarkerFloor(Uri uri) {
return uri.getPathSegments().get(2);
}
}
public static class SearchSuggest {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();
public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1
+ " COLLATE NOCASE ASC";
}
public static class SearchIndex {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_INDEX).build();
}
public static Uri addCallerIsSyncAdapterParameter(Uri uri) {
return uri.buildUpon().appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
}
public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {
return TextUtils.equals("true",
uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));
}
private ScheduleContract() {
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.app.Service;
import android.content.Intent;
import android.os.*;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.AccountUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.turbomanage.httpclient.AsyncCallback;
import com.turbomanage.httpclient.HttpResponse;
import com.turbomanage.httpclient.ParameterMap;
import com.turbomanage.httpclient.android.AndroidHttpClient;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Background {@link android.app.Service} that adds or removes sessions from your calendar via the
* Conference API.
*
* @see com.google.android.apps.iosched.sync.SyncHelper
*/
public class ScheduleUpdaterService extends Service {
private static final String TAG = makeLogTag(ScheduleUpdaterService.class);
public static final String EXTRA_SESSION_ID
= "com.google.android.apps.iosched.extra.SESSION_ID";
public static final String EXTRA_IN_SCHEDULE
= "com.google.android.apps.iosched.extra.IN_SCHEDULE";
private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000;
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>();
// Handler pattern copied from IntentService
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
processPendingScheduleUpdates();
int numRemainingUpdates;
synchronized (mScheduleUpdates) {
numRemainingUpdates = mScheduleUpdates.size();
}
if (numRemainingUpdates == 0) {
notifyGcmDevices();
stopSelf();
} else {
// More updates were added since the current pending set was processed. Reschedule
// another pass.
removeMessages(0);
sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
}
}
}
// private static class NotifyGcmDevicesTask extends AsyncTask<String, Void, Void> {
//
// @Override
// protected Void doInBackground(String... params) {
// BasicHttp
// String gPlusID = params[0];
// Uri uri = new Uri(Config.GCM_SERVER_URL + "/send/" + gPlusID + "/sync_user");
// connection = (HttpURLConnection) url.openConnection();
// connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setRequestMethod("POST");
//
// request = new OutputStreamWriter(connection.getOutputStream());
// request.write(parameters);
// request.flush();
// request.close();
//
// }
// }
private void notifyGcmDevices() {
String plusID = AccountUtils.getPlusProfileId(getApplicationContext());
if (plusID != null) {
LOGI(TAG, "Sending device sync notification");
AndroidHttpClient httpClient = new AndroidHttpClient(Config.GCM_SERVER_URL);
httpClient.setMaxRetries(1);
ParameterMap params = httpClient.newParams()
.add("key", Config.GCM_API_KEY)
.add("squelch", ServerUtilities.getGcmId(this));
String path = "/send/" + plusID + "/sync_user";
httpClient.post(path, params, new AsyncCallback() {
@Override
public void onComplete(HttpResponse httpResponse) {
LOGI(TAG, "Device sync notification sent");
}
@Override
public void onError(Exception e) {
LOGW(TAG, "Device sync notification failed", e);
}
});
} else {
LOGI(TAG, "No gPlusID, skipping device sync notification");
}
}
public ScheduleUpdaterService() {
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName());
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// When receiving a new intent, delay the schedule until 5 seconds from now.
mServiceHandler.removeMessages(0);
mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
// Remove pending updates involving this session ID.
String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
Iterator<Intent> updatesIterator = mScheduleUpdates.iterator();
while (updatesIterator.hasNext()) {
Intent existingIntent = updatesIterator.next();
if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) {
updatesIterator.remove();
}
}
// Queue this schedule update.
synchronized (mScheduleUpdates) {
mScheduleUpdates.add(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.UIUtils;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An I/O 2013 extension for DashClock.
*/
public class DashClockExtension extends com.google.android.apps.dashclock.api.DashClockExtension {
private static final String TAG = makeLogTag(DashClockExtension.class);
private static final long MINUTE_MILLIS = 60 * 1000;
private static final long NOW_BUFFER_TIME_MILLIS = 15 * MINUTE_MILLIS;
private static final int MAX_BLOCKS = 5;
private static final long CONTENT_CHANGE_DELAY_MILLIS = 5 * 1000;
private static long mLastChange = 0;
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
setUpdateWhenScreenOn(true);
addWatchContentUris(new String[]{
ScheduleContract.Sessions.CONTENT_URI.toString()
});
}
@Override
protected void onUpdateData(int reason) {
if (reason == DashClockExtension.UPDATE_REASON_CONTENT_CHANGED) {
long time = System.currentTimeMillis();
if (time < mLastChange + CONTENT_CHANGE_DELAY_MILLIS) {
return;
}
mLastChange = time;
}
long currentTime = UIUtils.getCurrentTime(this);
if (currentTime >= UIUtils.CONFERENCE_END_MILLIS) {
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.dashclock_extension)
.status(getString(R.string.whats_on_thank_you_short))
.expandedTitle(getString(R.string.whats_on_thank_you_title))
.expandedBody(getString(R.string.whats_on_thank_you_subtitle))
.clickIntent(new Intent(this, HomeActivity.class)));
return;
}
Cursor cursor = tryOpenBlocksCursor();
if (cursor == null) {
LOGE(TAG, "Null blocks cursor, short-circuiting.");
return;
}
StringBuilder buffer = new StringBuilder();
Formatter formatter = new Formatter(buffer, Locale.getDefault());
String firstBlockStartTime = null;
List<String> blocks = new ArrayList<String>();
long lastBlockStart = 0;
while (cursor.moveToNext()) {
if (blocks.size() >= MAX_BLOCKS) {
break;
}
final String type = cursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE);
final String blockType = cursor.getString(BlocksQuery.BLOCK_TYPE);
final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START);
buffer.setLength(0);
boolean showWeekday = !DateUtils.isToday(blockStart)
&& !UIUtils.isSameDayDisplay(lastBlockStart, blockStart, this);
String blockStartTime = DateUtils.formatDateRange(this, formatter,
blockStart, blockStart,
DateUtils.FORMAT_SHOW_TIME | (showWeekday
? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY
: 0),
PrefUtils.getDisplayTimeZone(this).getID()).toString();
lastBlockStart = blockStart;
if (firstBlockStartTime == null) {
firstBlockStartTime = blockStartTime;
}
if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) {
final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
if (numStarredSessions == 1) {
// exactly 1 session starred
String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
String room = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (room == null) {
room = getString(R.string.unknown_room);
}
blocks.add(blockStartTime + ", " + room + " — " + title);
} else {
// 2 or more sessions starred
String title = getString(R.string.schedule_conflict_title,
numStarredSessions);
blocks.add(blockStartTime + " — " + title);
}
} else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) {
final String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
blocks.add(blockStartTime + " — " + title);
} else {
blocks.add(blockStartTime + " — " + blockTitle);
}
}
cursor.close();
LOGD(TAG, blocks.size() + " blocks");
if (blocks.size() > 0) {
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.dashclock_extension)
.status(firstBlockStartTime)
.expandedTitle(blocks.get(0))
.expandedBody(TextUtils.join("\n", blocks.subList(1, blocks.size())))
.clickIntent(new Intent(this, HomeActivity.class)));
} else {
publishUpdate(new ExtensionData().visible(false));
}
}
private Cursor tryOpenBlocksCursor() {
try {
String liveStreamedOnlyBlocksSelection = "("
+ (UIUtils.shouldShowLiveSessionsOnly(this)
? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('"
+ ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')"
+ " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 "
: "1==1") + ")";
String onlyStarredSelection = "("
+ ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('"
+ ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "') "
+ " OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)";
String excludeSandbox = ScheduleContract.Blocks.BLOCK_TYPE + " != '"
+ ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX + "'";
return getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
ScheduleContract.Blocks.BLOCK_START + " >= ? AND "
+ liveStreamedOnlyBlocksSelection + " AND "
+ onlyStarredSelection + " AND "
+ excludeSandbox,
new String[]{
Long.toString(UIUtils.getCurrentTime(this) - NOW_BUFFER_TIME_MILLIS)
},
ScheduleContract.Blocks.DEFAULT_SORT);
} catch (Exception e) {
LOGE(TAG, "Error querying I/O 2013 content provider", e);
return null;
}
}
public interface BlocksQuery {
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Blocks.BLOCK_TITLE,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_TYPE,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS,
};
int _ID = 0;
int BLOCK_TITLE = 1;
int BLOCK_START = 2;
int BLOCK_TYPE = 3;
int NUM_STARRED_SESSIONS = 4;
int STARRED_SESSION_TITLE = 5;
int STARRED_SESSION_ROOM_NAME = 6;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.graphics.Bitmap;
import android.provider.BaseColumns;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background service to handle scheduling of starred session notification via
* {@link android.app.AlarmManager}.
*/
public class SessionAlarmService extends IntentService {
private static final String TAG = makeLogTag(SessionAlarmService.class);
public static final String ACTION_NOTIFY_SESSION =
"com.google.android.apps.iosched.action.NOTIFY_SESSION";
public static final String ACTION_SCHEDULE_STARRED_BLOCK =
"com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK";
public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS =
"com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS";
public static final String EXTRA_SESSION_START =
"com.google.android.apps.iosched.extra.SESSION_START";
public static final String EXTRA_SESSION_END =
"com.google.android.apps.iosched.extra.SESSION_END";
public static final String EXTRA_SESSION_ALARM_OFFSET =
"com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET";
private static final int NOTIFICATION_ID = 100;
// pulsate every 1 second, indicating a relatively high degree of urgency
private static final int NOTIFICATION_LED_ON_MS = 100;
private static final int NOTIFICATION_LED_OFF_MS = 1000;
private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan
private static final long MILLI_TEN_MINUTES = 600000;
private static final long MILLI_ONE_MINUTE = 60000;
private static final long UNDEFINED_ALARM_OFFSET = -1;
private static final long UNDEFINED_VALUE = -1;
public SessionAlarmService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) {
scheduleAllStarredBlocks();
return;
}
final long sessionStart =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, UNDEFINED_VALUE);
if (sessionStart == UNDEFINED_VALUE) return;
final long sessionEnd =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, UNDEFINED_VALUE);
if (sessionEnd == UNDEFINED_VALUE) return;
final long sessionAlarmOffset =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
UNDEFINED_ALARM_OFFSET);
if (ACTION_NOTIFY_SESSION.equals(action)) {
notifySession(sessionStart, sessionEnd, sessionAlarmOffset);
} else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) {
scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset);
}
}
private void scheduleAlarm(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
final long currentTime = UIUtils.getCurrentTime(this);
// If the session is already started, do not schedule system notification.
if (currentTime > sessionStart) return;
// By default, sets alarm to go off at 10 minutes before session start time. If alarm
// offset is provided, alarm is set to go off by that much time from now.
long alarmTime;
if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
alarmTime = sessionStart - MILLI_TEN_MINUTES;
} else {
alarmTime = currentTime + alarmOffset;
}
final Intent notifIntent = new Intent(
ACTION_NOTIFY_SESSION,
null,
this,
SessionAlarmService.class);
// Setting data to ensure intent's uniqueness for different session start times.
notifIntent.setData(
new Uri.Builder().authority("com.google.android.apps.iosched")
.path(String.valueOf(sessionStart)).build());
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
PendingIntent pi = PendingIntent.getService(this,
0,
notifIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Schedule an alarm to be fired to notify user of added sessions are about to begin.
am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}
// Starred sessions are about to begin. Constructs and triggers system notification.
private void notifySession(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
long currentTime;
if (sessionStart < (currentTime = UIUtils.getCurrentTime(this))) return;
// Avoid repeated notifications.
if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(
this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
return;
}
final ContentResolver cr = getContentResolver();
final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri(
ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd)
);
Cursor c = cr.query(starredBlockUri,
SessionDetailQuery.PROJECTION,
null,
null,
null);
int starredCount = 0;
ArrayList<String> starredSessionTitles = new ArrayList<String>();
ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
String sessionId = null; // needed to get session track icon
while (c.moveToNext()) {
sessionId = c.getString(SessionDetailQuery.SESSION_ID);
starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
}
if (starredCount < 1) {
return;
}
// Generates the pending intent which gets fired when the user taps on the notification.
// NOTE: Use TaskStackBuilder to comply with Android's design guidelines
// related to navigation from notifications.
PendingIntent pi = TaskStackBuilder.create(this)
.addNextIntent(new Intent(this, HomeActivity.class))
.addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
final Resources res = getResources();
String contentText;
int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
if (minutesLeft < 1) {
minutesLeft = 1;
}
if (starredCount == 1) {
contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
} else {
contentText = res.getQuantityString(R.plurals.session_notification_text,
starredCount - 1,
minutesLeft,
starredCount - 1);
}
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
if (starredCount == 1) {
// get the track icon to show as the notification big picture
Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION,
null, null, null);
if (tracksCursor.moveToFirst()) {
String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(),
trackName, trackColour);
if (trackIcon != null) {
notifBuilder.setLargeIcon(trackIcon);
}
}
}
if (minutesLeft > 5) {
notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
String.format(res.getString(R.string.snooze_x_min), 5),
createSnoozeIntent(sessionStart, sessionEnd, 5));
}
if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) {
notifBuilder.addAction(R.drawable.ic_map_holo_dark,
res.getString(R.string.title_map),
createRoomMapIntent(starredSessionRoomIds.get(0)));
}
NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(
notifBuilder)
.setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title,
starredCount,
minutesLeft,
starredCount));
// Adds starred sessions starting at this time block to the notification.
for (int i = 0; i < starredCount; i++) {
richNotification.addLine(starredSessionTitles.get(i));
}
NotificationManager nm = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, richNotification.build());
}
private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
final int snoozeMinutes) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, this, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
snoozeMinutes * MILLI_ONE_MINUTE);
return PendingIntent.getService(this, 0, scheduleIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private PendingIntent createRoomMapIntent(final String roomId) {
Intent mapIntent = new Intent(getApplicationContext(),
UIUtils.getMapActivityClass(getApplicationContext()));
mapIntent.putExtra(MapFragment.EXTRA_ROOM, roomId);
return PendingIntent.getActivity(this, 0, mapIntent, 0);
}
private void scheduleAllStarredBlocks() {
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_STARRED_URI,
new String[]{"distinct " + ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END},
null,
null,
null);
if (c == null) {
return;
}
while (c.moveToNext()) {
final long sessionStart = c.getLong(0);
final long sessionEnd = c.getLong(1);
scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
}
}
public interface SessionDetailQuery {
String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.ROOM_ID
};
int SESSION_ID = 0;
int NUM_STARRED_SESSIONS = 1;
int SESSION_TITLE = 2;
int ROOM_ID = 3;
}
public interface SessionTrackQuery {
String[] PROJECTION = {
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR
};
int TRACK_ID = 0;
int TRACK_NAME = 1;
int TRACK_COLOR = 2;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.android.apps.iosched.service.SessionAlarmService;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
/**
* {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing
* then against fractional dimensions of the source view.
* <p>
* This is particularly useful when you want to define a rectangle in terms of
* the source dimensions, but when those dimensions might change due to pending
* or future layout passes.
* <p>
* One example is catching touches that occur in the top-right quadrant of
* {@code sourceParent}, and relaying them to {@code targetChild}. This could be
* done with: <code>
* FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f));
* </code>
*/
public class FractionalTouchDelegate extends TouchDelegate {
private View mSource;
private View mTarget;
private RectF mSourceFraction;
private Rect mScrap = new Rect();
/** Cached full dimensions of {@link #mSource}. */
private Rect mSourceFull = new Rect();
/** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */
private Rect mSourcePartial = new Rect();
private boolean mDelegateTargeted;
public FractionalTouchDelegate(View source, View target, RectF sourceFraction) {
super(new Rect(0, 0, 0, 0), target);
mSource = source;
mTarget = target;
mSourceFraction = sourceFraction;
}
/**
* Helper to create and setup a {@link FractionalTouchDelegate} between the
* given {@link View}.
*
* @param source Larger source {@link View}, usually a parent, that will be
* assigned {@link View#setTouchDelegate(TouchDelegate)}.
* @param target Smaller target {@link View} which will receive
* {@link MotionEvent} that land in requested fractional area.
* @param sourceFraction Fractional area projected onto source {@link View}
* which determines when {@link MotionEvent} will be passed to
* target {@link View}.
*/
public static void setupDelegate(View source, View target, RectF sourceFraction) {
source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
/**
* Consider updating {@link #mSourcePartial} when {@link #mSource}
* dimensions have changed.
*/
private void updateSourcePartial() {
mSource.getHitRect(mScrap);
if (!mScrap.equals(mSourceFull)) {
// Copy over and calculate fractional rectangle
mSourceFull.set(mScrap);
final int width = mSourceFull.width();
final int height = mSourceFull.height();
mSourcePartial.left = (int) (mSourceFraction.left * width);
mSourcePartial.top = (int) (mSourceFraction.top * height);
mSourcePartial.right = (int) (mSourceFraction.right * width);
mSourcePartial.bottom = (int) (mSourceFraction.bottom * height);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
updateSourcePartial();
// The logic below is mostly copied from the parent class, since we
// can't update private mBounds variable.
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
// f=core/java/android/view/TouchDelegate.java;hb=eclair#l98
final Rect sourcePartial = mSourcePartial;
final View target = mTarget;
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (sourcePartial.contains(x, y)) {
mDelegateTargeted = true;
sendToDelegate = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
if (!sourcePartial.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
if (hit) {
event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
} else {
event.setLocation(-1, -1);
}
handled = target.dispatchTouchEvent(event);
}
return handled;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.