code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* Copyright (C) 2008 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.downloader;
import android.app.Activity;
import android.content.Intent;
/**
* Usage:
*
* Intent intent = PreconditionActivityHelper.createPreconditionIntent(
* activity, WaitActivity.class);
* // Optionally add extras to pass arguments to the intent
* intent.putExtra(Utils.EXTRA_ACCOUNT, account);
* PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent);
*
* // And in the wait activity:
* PreconditionActivityHelper.startOriginalActivityAndFinish(this);
*
*/
public class PreconditionActivityHelper {
/**
* Create a precondition activity intent.
* @param activity the original activity
* @param preconditionActivityClazz the precondition activity's class
* @return an intent which will launch the precondition activity.
*/
public static Intent createPreconditionIntent(Activity activity,
Class preconditionActivityClazz) {
Intent newIntent = new Intent();
newIntent.setClass(activity, preconditionActivityClazz);
newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent());
return newIntent;
}
/**
* Start the precondition activity using a given intent, which should
* have been created by calling createPreconditionIntent.
* @param activity
* @param intent
*/
public static void startPreconditionActivityAndFinish(Activity activity,
Intent intent) {
activity.startActivity(intent);
activity.finish();
}
/**
* Start the original activity, and finish the precondition activity.
* @param preconditionActivity
*/
public static void startOriginalActivityAndFinish(
Activity preconditionActivity) {
preconditionActivity.startActivity(
(Intent) preconditionActivity.getIntent()
.getParcelableExtra(EXTRA_WRAPPED_INTENT));
preconditionActivity.finish();
}
static private final String EXTRA_WRAPPED_INTENT =
"PreconditionActivityHelper_wrappedIntent";
}
| Java |
package com.google.android.webviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
/**
* Demonstrates how to embed a WebView in your activity. Also demonstrates how
* to have javascript in the WebView call into the activity, and how the activity
* can invoke javascript.
* <p>
* In this example, clicking on the android in the WebView will result in a call into
* the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code
* will turn around and invoke javascript using the {@link WebView#loadUrl(String)}
* method.
* <p>
* Obviously all of this could have been accomplished without calling into the activity
* and then back into javascript, but this code is intended to show how to set up the
* code paths for this sort of communication.
*
*/
public class WebViewDemo extends Activity {
private static final String LOG_TAG = "WebViewDemo";
private WebView mWebView;
private Handler mHandler = new Handler();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setWebChromeClient(new MyWebChromeClient());
mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo");
mWebView.loadUrl("file:///android_asset/demo.html");
}
final class DemoJavaScriptInterface {
DemoJavaScriptInterface() {
}
/**
* This is not called on the UI thread. Post a runnable to invoke
* loadUrl on the UI thread.
*/
public void clickOnAndroid() {
mHandler.post(new Runnable() {
public void run() {
mWebView.loadUrl("javascript:wave()");
}
});
}
}
/**
* Provides a hook for calling "alert" from javascript. Useful for
* debugging your javascript.
*/
final class MyWebChromeClient extends WebChromeClient {
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
Log.d(LOG_TAG, message);
result.confirm();
return true;
}
}
} | Java |
/*
* Copyright (C) 2008 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.opengles.spritetext;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Paint;
public class NumericSprite {
public NumericSprite() {
mText = "";
mLabelMaker = null;
}
public void initialize(GL10 gl, Paint paint) {
int height = roundUpPower2((int) paint.getFontSpacing());
final float interDigitGaps = 9 * 1.0f;
int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike)));
mLabelMaker = new LabelMaker(true, width, height);
mLabelMaker.initialize(gl);
mLabelMaker.beginAdding(gl);
for (int i = 0; i < 10; i++) {
String digit = sStrike.substring(i, i+1);
mLabelId[i] = mLabelMaker.add(gl, digit, paint);
mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i));
}
mLabelMaker.endAdding(gl);
}
public void shutdown(GL10 gl) {
mLabelMaker.shutdown(gl);
mLabelMaker = null;
}
/**
* Find the smallest power of two >= the input value.
* (Doesn't work for negative numbers.)
*/
private int roundUpPower2(int x) {
x = x - 1;
x = x | (x >> 1);
x = x | (x >> 2);
x = x | (x >> 4);
x = x | (x >> 8);
x = x | (x >>16);
return x + 1;
}
public void setValue(int value) {
mText = format(value);
}
public void draw(GL10 gl, float x, float y,
float viewWidth, float viewHeight) {
int length = mText.length();
mLabelMaker.beginDrawing(gl, viewWidth, viewHeight);
for(int i = 0; i < length; i++) {
char c = mText.charAt(i);
int digit = c - '0';
mLabelMaker.draw(gl, x, y, mLabelId[digit]);
x += mWidth[digit];
}
mLabelMaker.endDrawing(gl);
}
public float width() {
float width = 0.0f;
int length = mText.length();
for(int i = 0; i < length; i++) {
char c = mText.charAt(i);
width += mWidth[c - '0'];
}
return width;
}
private String format(int value) {
return Integer.toString(value);
}
private LabelMaker mLabelMaker;
private String mText;
private int[] mWidth = new int[10];
private int[] mLabelId = new int[10];
private final static String sStrike = "0123456789";
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import android.opengl.Matrix;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/**
* A matrix stack, similar to OpenGL ES's internal matrix stack.
*/
public class MatrixStack {
public MatrixStack() {
commonInit(DEFAULT_MAX_DEPTH);
}
public MatrixStack(int maxDepth) {
commonInit(maxDepth);
}
private void commonInit(int maxDepth) {
mMatrix = new float[maxDepth * MATRIX_SIZE];
mTemp = new float[MATRIX_SIZE * 2];
glLoadIdentity();
}
public void glFrustumf(float left, float right, float bottom, float top,
float near, float far) {
Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far);
}
public void glFrustumx(int left, int right, int bottom, int top, int near,
int far) {
glFrustumf(fixedToFloat(left),fixedToFloat(right),
fixedToFloat(bottom), fixedToFloat(top),
fixedToFloat(near), fixedToFloat(far));
}
public void glLoadIdentity() {
Matrix.setIdentityM(mMatrix, mTop);
}
public void glLoadMatrixf(float[] m, int offset) {
System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE);
}
public void glLoadMatrixf(FloatBuffer m) {
m.get(mMatrix, mTop, MATRIX_SIZE);
}
public void glLoadMatrixx(int[] m, int offset) {
for(int i = 0; i < MATRIX_SIZE; i++) {
mMatrix[mTop + i] = fixedToFloat(m[offset + i]);
}
}
public void glLoadMatrixx(IntBuffer m) {
for(int i = 0; i < MATRIX_SIZE; i++) {
mMatrix[mTop + i] = fixedToFloat(m.get());
}
}
public void glMultMatrixf(float[] m, int offset) {
System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE);
Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset);
}
public void glMultMatrixf(FloatBuffer m) {
m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE);
glMultMatrixf(mTemp, MATRIX_SIZE);
}
public void glMultMatrixx(int[] m, int offset) {
for(int i = 0; i < MATRIX_SIZE; i++) {
mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]);
}
glMultMatrixf(mTemp, MATRIX_SIZE);
}
public void glMultMatrixx(IntBuffer m) {
for(int i = 0; i < MATRIX_SIZE; i++) {
mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get());
}
glMultMatrixf(mTemp, MATRIX_SIZE);
}
public void glOrthof(float left, float right, float bottom, float top,
float near, float far) {
Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far);
}
public void glOrthox(int left, int right, int bottom, int top, int near,
int far) {
glOrthof(fixedToFloat(left), fixedToFloat(right),
fixedToFloat(bottom), fixedToFloat(top),
fixedToFloat(near), fixedToFloat(far));
}
public void glPopMatrix() {
preflight_adjust(-1);
adjust(-1);
}
public void glPushMatrix() {
preflight_adjust(1);
System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE,
MATRIX_SIZE);
adjust(1);
}
public void glRotatef(float angle, float x, float y, float z) {
Matrix.setRotateM(mTemp, 0, angle, x, y, z);
System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE);
Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0);
}
public void glRotatex(int angle, int x, int y, int z) {
glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z));
}
public void glScalef(float x, float y, float z) {
Matrix.scaleM(mMatrix, mTop, x, y, z);
}
public void glScalex(int x, int y, int z) {
glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z));
}
public void glTranslatef(float x, float y, float z) {
Matrix.translateM(mMatrix, mTop, x, y, z);
}
public void glTranslatex(int x, int y, int z) {
glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z));
}
public void getMatrix(float[] dest, int offset) {
System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE);
}
private float fixedToFloat(int x) {
return x * (1.0f / 65536.0f);
}
private void preflight_adjust(int dir) {
int newTop = mTop + dir * MATRIX_SIZE;
if (newTop < 0) {
throw new IllegalArgumentException("stack underflow");
}
if (newTop + MATRIX_SIZE > mMatrix.length) {
throw new IllegalArgumentException("stack overflow");
}
}
private void adjust(int dir) {
mTop += dir * MATRIX_SIZE;
}
private final static int DEFAULT_MAX_DEPTH = 32;
private final static int MATRIX_SIZE = 16;
private float[] mMatrix;
private int mTop;
private float[] mTemp;
}
| Java |
/*
* Copyright (C) 2008 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.opengles.spritetext;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.SystemClock;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
public class SpriteTextRenderer implements GLView.Renderer{
public SpriteTextRenderer(Context context) {
mContext = context;
mTriangle = new Triangle();
mProjector = new Projector();
mLabelPaint = new Paint();
mLabelPaint.setTextSize(32);
mLabelPaint.setAntiAlias(true);
mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00);
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_NONE
};
return configSpec;
}
public void surfaceCreated(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
/*
* Some one-time OpenGL initialization can be made here
* probably based on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
GL10.GL_FASTEST);
gl.glClearColor(.5f, .5f, .5f, 1);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* Create our texture. This has to be done each time the
* surface is created.
*/
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
InputStream is = mContext.getResources()
.openRawResource(R.drawable.tex);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
} catch(IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
if (mLabels != null) {
mLabels.shutdown(gl);
} else {
mLabels = new LabelMaker(true, 256, 64);
}
mLabels.initialize(gl);
mLabels.beginAdding(gl);
mLabelA = mLabels.add(gl, "A", mLabelPaint);
mLabelB = mLabels.add(gl, "B", mLabelPaint);
mLabelC = mLabels.add(gl, "C", mLabelPaint);
mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint);
mLabels.endAdding(gl);
if (mNumericSprite != null) {
mNumericSprite.shutdown(gl);
} else {
mNumericSprite = new NumericSprite();
}
mNumericSprite.initialize(gl, mLabelPaint);
}
public void drawFrame(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
/*
* Usually, the first thing one might want to do is to clear
* the screen. The most efficient way of doing this is to use
* glClear().
*/
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
/*
* Now we're ready to draw some 3D objects
*/
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glActiveTexture(GL10.GL_TEXTURE0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
gl.glRotatef(angle, 0, 0, 1.0f);
gl.glScalef(2.0f, 2.0f, 2.0f);
mTriangle.draw(gl);
mProjector.getCurrentModelView(gl);
mLabels.beginDrawing(gl, mWidth, mHeight);
drawLabel(gl, 0, mLabelA);
drawLabel(gl, 1, mLabelB);
drawLabel(gl, 2, mLabelC);
float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1;
mLabels.draw(gl, msPFX, 0, mLabelMsPF);
mLabels.endDrawing(gl);
drawMsPF(gl, msPFX);
}
private void drawMsPF(GL10 gl, float rightMargin) {
long time = SystemClock.uptimeMillis();
if (mStartTime == 0) {
mStartTime = time;
}
if (mFrames++ == SAMPLE_PERIOD_FRAMES) {
mFrames = 0;
long delta = time - mStartTime;
mStartTime = time;
mMsPerFrame = (int) (delta * SAMPLE_FACTOR);
}
if (mMsPerFrame > 0) {
mNumericSprite.setValue(mMsPerFrame);
float numWidth = mNumericSprite.width();
float x = rightMargin - numWidth;
mNumericSprite.draw(gl, x, 0, mWidth, mHeight);
}
}
private void drawLabel(GL10 gl, int triangleVertex, int labelId) {
float x = mTriangle.getX(triangleVertex);
float y = mTriangle.getY(triangleVertex);
mScratch[0] = x;
mScratch[1] = y;
mScratch[2] = 0.0f;
mScratch[3] = 1.0f;
mProjector.project(mScratch, 0, mScratch, 4);
float sx = mScratch[4];
float sy = mScratch[5];
float height = mLabels.getHeight(labelId);
float width = mLabels.getWidth(labelId);
float tx = sx - width * 0.5f;
float ty = sy - height * 0.5f;
mLabels.draw(gl, tx, ty, labelId);
}
public void sizeChanged(GL10 gl, int w, int h) {
mWidth = w;
mHeight = h;
gl.glViewport(0, 0, w, h);
mProjector.setCurrentView(0, 0, w, h);
/*
* Set our projection matrix. This doesn't have to be done
* each time we draw, but usually a new projection needs to
* be set when the viewport is resized.
*/
float ratio = (float) w / h;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10);
mProjector.getCurrentProjection(gl);
}
private int mWidth;
private int mHeight;
private Context mContext;
private Triangle mTriangle;
private int mTextureID;
private int mFrames;
private int mMsPerFrame;
private final static int SAMPLE_PERIOD_FRAMES = 12;
private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES;
private long mStartTime;
private LabelMaker mLabels;
private Paint mLabelPaint;
private int mLabelA;
private int mLabelB;
private int mLabelC;
private int mLabelMsPF;
private Projector mProjector;
private NumericSprite mNumericSprite;
private float[] mScratch = new float[8];
}
class Triangle {
public Triangle() {
// Buffers to be passed to gl*Pointer() functions
// must be direct, i.e., they must be placed on the
// native heap where the garbage collector cannot
// move them.
//
// Buffers with multi-byte datatypes (e.g., short, int, float)
// must have their byte order set to native order
ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mFVertexBuffer = vbb.asFloatBuffer();
ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexBuffer = tbb.asFloatBuffer();
ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2);
ibb.order(ByteOrder.nativeOrder());
mIndexBuffer = ibb.asShortBuffer();
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 3; j++) {
mFVertexBuffer.put(sCoords[i*3+j]);
}
}
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 2; j++) {
mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f);
}
}
for(int i = 0; i < VERTS; i++) {
mIndexBuffer.put((short) i);
}
mFVertexBuffer.position(0);
mTexBuffer.position(0);
mIndexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glFrontFace(GL10.GL_CCW);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
}
public float getX(int vertex) {
return sCoords[3*vertex];
}
public float getY(int vertex) {
return sCoords[3*vertex+1];
}
private final static int VERTS = 3;
private FloatBuffer mFVertexBuffer;
private FloatBuffer mTexBuffer;
private ShortBuffer mIndexBuffer;
// A unit-sided equalateral triangle centered on the origin.
private final static float[] sCoords = {
// X, Y, Z
-0.5f, -0.25f, 0,
0.5f, -0.25f, 0,
0.0f, 0.559016994f, 0
};
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import javax.microedition.khronos.opengles.GL10;
class MatrixGrabber {
public MatrixGrabber() {
mModelView = new float[16];
mProjection = new float[16];
}
/**
* Record the current modelView and projection matrix state.
* Has the side effect of setting the current matrix state to GL_MODELVIEW
* @param gl
*/
public void getCurrentState(GL10 gl) {
getCurrentProjection(gl);
getCurrentModelView(gl);
}
/**
* Record the current modelView matrix state. Has the side effect of
* setting the current matrix state to GL_MODELVIEW
* @param gl
*/
public void getCurrentModelView(GL10 gl) {
getMatrix(gl, GL10.GL_MODELVIEW, mModelView);
}
/**
* Record the current projection matrix state. Has the side effect of
* setting the current matrix state to GL_PROJECTION
* @param gl
*/
public void getCurrentProjection(GL10 gl) {
getMatrix(gl, GL10.GL_PROJECTION, mProjection);
}
private void getMatrix(GL10 gl, int mode, float[] mat) {
MatrixTrackingGL gl2 = (MatrixTrackingGL) gl;
gl2.glMatrixMode(mode);
gl2.getMatrix(mat, 0);
}
public float[] mModelView;
public float[] mProjection;
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.opengl.GLUtils;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* An OpenGL text label maker.
*
*
* OpenGL labels are implemented by creating a Bitmap, drawing all the labels
* into the Bitmap, converting the Bitmap into an Alpha texture, and creating a
* mesh for each label
*
* The benefits of this approach are that the labels are drawn using the high
* quality anti-aliased font rasterizer, full character set support, and all the
* text labels are stored on a single texture, which makes it faster to use.
*
* The drawbacks are that you can only have as many labels as will fit onto one
* texture, and you have to recreate the whole texture if any label text
* changes.
*
*/
public class LabelMaker {
/**
* Create a label maker
* or maximum compatibility with various OpenGL ES implementations,
* the strike width and height must be powers of two,
* We want the strike width to be at least as wide as the widest window.
*
* @param fullColor true if we want a full color backing store (4444),
* otherwise we generate a grey L8 backing store.
* @param strikeWidth width of strike
* @param strikeHeight height of strike
*/
public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) {
mFullColor = fullColor;
mStrikeWidth = strikeWidth;
mStrikeHeight = strikeHeight;
mTexelWidth = (float) (1.0 / mStrikeWidth);
mTexelHeight = (float) (1.0 / mStrikeHeight);
mClearPaint = new Paint();
mClearPaint.setARGB(0, 0, 0, 0);
mClearPaint.setStyle(Style.FILL);
mState = STATE_NEW;
}
/**
* Call to initialize the class.
* Call whenever the surface has been created.
*
* @param gl
*/
public void initialize(GL10 gl) {
mState = STATE_INITIALIZED;
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
// Use Nearest for performance.
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
}
/**
* Call when the surface has been destroyed
*/
public void shutdown(GL10 gl) {
if ( gl != null) {
if (mState > STATE_NEW) {
int[] textures = new int[1];
textures[0] = mTextureID;
gl.glDeleteTextures(1, textures, 0);
mState = STATE_NEW;
}
}
}
/**
* Call before adding labels. Clears out any existing labels.
*
* @param gl
*/
public void beginAdding(GL10 gl) {
checkState(STATE_INITIALIZED, STATE_ADDING);
mLabels.clear();
mU = 0;
mV = 0;
mLineHeight = 0;
Bitmap.Config config = mFullColor ?
Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8;
mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config);
mCanvas = new Canvas(mBitmap);
mBitmap.eraseColor(0);
}
/**
* Call to add a label
*
* @param gl
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, String text, Paint textPaint) {
return add(gl, null, text, textPaint);
}
/**
* Call to add a label
*
* @param gl
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, String text, Paint textPaint) {
return add(gl, background, text, textPaint, 0, 0);
}
/**
* Call to add a label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) {
return add(gl, drawable, null, null, minWidth, minHeight);
}
/**
* Call to add a label
*
* @param gl
* @param text the text of the label
* @param textPaint the paint of the label
* @return the id of the label, used to measure and draw the label
*/
public int add(GL10 gl, Drawable background, String text, Paint textPaint,
int minWidth, int minHeight) {
checkState(STATE_ADDING, STATE_ADDING);
boolean drawBackground = background != null;
boolean drawText = (text != null) && (textPaint != null);
Rect padding = new Rect();
if (drawBackground) {
background.getPadding(padding);
minWidth = Math.max(minWidth, background.getMinimumWidth());
minHeight = Math.max(minHeight, background.getMinimumHeight());
}
int ascent = 0;
int descent = 0;
int measuredTextWidth = 0;
if (drawText) {
// Paint.ascent is negative, so negate it.
ascent = (int) Math.ceil(-textPaint.ascent());
descent = (int) Math.ceil(textPaint.descent());
measuredTextWidth = (int) Math.ceil(textPaint.measureText(text));
}
int textHeight = ascent + descent;
int textWidth = Math.min(mStrikeWidth,measuredTextWidth);
int padHeight = padding.top + padding.bottom;
int padWidth = padding.left + padding.right;
int height = Math.max(minHeight, textHeight + padHeight);
int width = Math.max(minWidth, textWidth + padWidth);
int effectiveTextHeight = height - padHeight;
int effectiveTextWidth = width - padWidth;
int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2;
int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2;
// Make changes to the local variables, only commit them
// to the member variables after we've decided not to throw
// any exceptions.
int u = mU;
int v = mV;
int lineHeight = mLineHeight;
if (width > mStrikeWidth) {
width = mStrikeWidth;
}
// Is there room for this string on the current line?
if (u + width > mStrikeWidth) {
// No room, go to the next line:
u = 0;
v += lineHeight;
lineHeight = 0;
}
lineHeight = Math.max(lineHeight, height);
if (v + lineHeight > mStrikeHeight) {
throw new IllegalArgumentException("Out of texture space.");
}
int u2 = u + width;
int vBase = v + ascent;
int v2 = v + height;
if (drawBackground) {
background.setBounds(u, v, u + width, v + height);
background.draw(mCanvas);
}
if (drawText) {
mCanvas.drawText(text,
u + padding.left + centerOffsetWidth,
vBase + padding.top + centerOffsetHeight,
textPaint);
}
Grid grid = new Grid(2, 2);
// Grid.set arguments: i, j, x, y, z, u, v
float texU = u * mTexelWidth;
float texU2 = u2 * mTexelWidth;
float texV = 1.0f - v * mTexelHeight;
float texV2 = 1.0f - v2 * mTexelHeight;
grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2);
grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2);
grid.set(0, 1, 0.0f, height, 0.0f, texU , texV );
grid.set(1, 1, width, height, 0.0f, texU2, texV );
// We know there's enough space, so update the member variables
mU = u + width;
mV = v;
mLineHeight = lineHeight;
mLabels.add(new Label(grid, width, height, ascent,
u, v + height, width, -height));
return mLabels.size() - 1;
}
/**
* Call to end adding labels. Must be called before drawing starts.
*
* @param gl
*/
public void endAdding(GL10 gl) {
checkState(STATE_ADDING, STATE_INITIALIZED);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0);
// Reclaim storage used by bitmap and canvas.
mBitmap.recycle();
mBitmap = null;
mCanvas = null;
}
/**
* Get the width in pixels of a given label.
*
* @param labelID
* @return the width in pixels
*/
public float getWidth(int labelID) {
return mLabels.get(labelID).width;
}
/**
* Get the height in pixels of a given label.
*
* @param labelID
* @return the height in pixels
*/
public float getHeight(int labelID) {
return mLabels.get(labelID).height;
}
/**
* Get the baseline of a given label. That's how many pixels from the top of
* the label to the text baseline. (This is equivalent to the negative of
* the label's paint's ascent.)
*
* @param labelID
* @return the baseline in pixels.
*/
public float getBaseline(int labelID) {
return mLabels.get(labelID).baseline;
}
/**
* Begin drawing labels. Sets the OpenGL state for rapid drawing.
*
* @param gl
* @param viewWidth
* @param viewHeight
*/
public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) {
checkState(STATE_INITIALIZED, STATE_DRAWING);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPushMatrix();
gl.glLoadIdentity();
// Magic offsets to promote consistent rasterization.
gl.glTranslatef(0.375f, 0.375f, 0.0f);
}
/**
* Draw a given label at a given x,y position, expressed in pixels, with the
* lower-left-hand-corner of the view being (0,0).
*
* @param gl
* @param x
* @param y
* @param labelID
*/
public void draw(GL10 gl, float x, float y, int labelID) {
checkState(STATE_DRAWING, STATE_DRAWING);
gl.glPushMatrix();
float snappedX = (float) Math.floor(x);
float snappedY = (float) Math.floor(y);
gl.glTranslatef(snappedX, snappedY, 0.0f);
Label label = mLabels.get(labelID);
gl.glEnable(GL10.GL_TEXTURE_2D);
((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0);
((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0,
(int) label.width, (int) label.height);
gl.glPopMatrix();
}
/**
* Ends the drawing and restores the OpenGL state.
*
* @param gl
*/
public void endDrawing(GL10 gl) {
checkState(STATE_DRAWING, STATE_INITIALIZED);
gl.glDisable(GL10.GL_BLEND);
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glPopMatrix();
}
private void checkState(int oldState, int newState) {
if (mState != oldState) {
throw new IllegalArgumentException("Can't call this method now.");
}
mState = newState;
}
private static class Label {
public Label(Grid grid, float width, float height, float baseLine,
int cropU, int cropV, int cropW, int cropH) {
this.grid = grid;
this.width = width;
this.height = height;
this.baseline = baseLine;
int[] crop = new int[4];
crop[0] = cropU;
crop[1] = cropV;
crop[2] = cropW;
crop[3] = cropH;
mCrop = crop;
}
public Grid grid;
public float width;
public float height;
public float baseline;
public int[] mCrop;
}
private int mStrikeWidth;
private int mStrikeHeight;
private boolean mFullColor;
private Bitmap mBitmap;
private Canvas mCanvas;
private Paint mClearPaint;
private int mTextureID;
private float mTexelWidth; // Convert texel to U
private float mTexelHeight; // Convert texel to V
private int mU;
private int mV;
private int mLineHeight;
private ArrayList<Label> mLabels = new ArrayList<Label>();
private static final int STATE_NEW = 0;
private static final int STATE_INITIALIZED = 1;
private static final int STATE_ADDING = 2;
private static final int STATE_DRAWING = 3;
private int mState;
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import android.opengl.Matrix;
import javax.microedition.khronos.opengles.GL10;
/**
* A utility that projects
*
*/
class Projector {
public Projector() {
mMVP = new float[16];
mV = new float[4];
mGrabber = new MatrixGrabber();
}
public void setCurrentView(int x, int y, int width, int height) {
mX = x;
mY = y;
mViewWidth = width;
mViewHeight = height;
}
public void project(float[] obj, int objOffset, float[] win, int winOffset) {
if (!mMVPComputed) {
Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0);
mMVPComputed = true;
}
Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset);
float rw = 1.0f / mV[3];
win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f;
win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f;
win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f;
}
/**
* Get the current projection matrix. Has the side-effect of
* setting current matrix mode to GL_PROJECTION
* @param gl
*/
public void getCurrentProjection(GL10 gl) {
mGrabber.getCurrentProjection(gl);
mMVPComputed = false;
}
/**
* Get the current model view matrix. Has the side-effect of
* setting current matrix mode to GL_MODELVIEW
* @param gl
*/
public void getCurrentModelView(GL10 gl) {
mGrabber.getCurrentModelView(gl);
mMVPComputed = false;
}
private MatrixGrabber mGrabber;
private boolean mMVPComputed;
private float[] mMVP;
private float[] mV;
private int mX;
private int mY;
private int mViewWidth;
private int mViewHeight;
}
| Java |
/*
* Copyright (C) 2008 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.opengles.spritetext;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
class GLView extends SurfaceView implements SurfaceHolder.Callback {
GLView(Context context) {
super(context);
init();
}
public GLView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
mGLThread.queueEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
Runnable r;
while ((r = getEvent()) != null) {
r.run();
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
/* draw a frame here */
mRenderer.drawFrame(gl);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
mEglHelper.swap();
}
}
/*
* clean-up everything...
*/
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
synchronized(this) {
mEventQueue.add(r);
}
}
private Runnable getEvent() {
synchronized(this) {
if (mEventQueue.size() > 0) {
return mEventQueue.remove(0);
}
}
return null;
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import android.util.Log;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL10Ext;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* Allows retrieving the current matrix even if the current OpenGL ES
* driver does not support retrieving the current matrix.
*
* Note: the actual matrix may differ from the retrieved matrix, due
* to differences in the way the math is implemented by GLMatrixWrapper
* as compared to the way the math is implemented by the OpenGL ES
* driver.
*/
class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext {
private GL10 mgl;
private GL10Ext mgl10Ext;
private GL11 mgl11;
private GL11Ext mgl11Ext;
private int mMatrixMode;
private MatrixStack mCurrent;
private MatrixStack mModelView;
private MatrixStack mTexture;
private MatrixStack mProjection;
private final static boolean _check = false;
ByteBuffer mByteBuffer;
FloatBuffer mFloatBuffer;
float[] mCheckA;
float[] mCheckB;
public MatrixTrackingGL(GL gl) {
mgl = (GL10) gl;
if (gl instanceof GL10Ext) {
mgl10Ext = (GL10Ext) gl;
}
if (gl instanceof GL11) {
mgl11 = (GL11) gl;
}
if (gl instanceof GL11Ext) {
mgl11Ext = (GL11Ext) gl;
}
mModelView = new MatrixStack();
mProjection = new MatrixStack();
mTexture = new MatrixStack();
mCurrent = mModelView;
mMatrixMode = GL10.GL_MODELVIEW;
}
// ---------------------------------------------------------------------
// GL10 methods:
public void glActiveTexture(int texture) {
mgl.glActiveTexture(texture);
}
public void glAlphaFunc(int func, float ref) {
mgl.glAlphaFunc(func, ref);
}
public void glAlphaFuncx(int func, int ref) {
mgl.glAlphaFuncx(func, ref);
}
public void glBindTexture(int target, int texture) {
mgl.glBindTexture(target, texture);
}
public void glBlendFunc(int sfactor, int dfactor) {
mgl.glBlendFunc(sfactor, dfactor);
}
public void glClear(int mask) {
mgl.glClear(mask);
}
public void glClearColor(float red, float green, float blue, float alpha) {
mgl.glClearColor(red, green, blue, alpha);
}
public void glClearColorx(int red, int green, int blue, int alpha) {
mgl.glClearColorx(red, green, blue, alpha);
}
public void glClearDepthf(float depth) {
mgl.glClearDepthf(depth);
}
public void glClearDepthx(int depth) {
mgl.glClearDepthx(depth);
}
public void glClearStencil(int s) {
mgl.glClearStencil(s);
}
public void glClientActiveTexture(int texture) {
mgl.glClientActiveTexture(texture);
}
public void glColor4f(float red, float green, float blue, float alpha) {
mgl.glColor4f(red, green, blue, alpha);
}
public void glColor4x(int red, int green, int blue, int alpha) {
mgl.glColor4x(red, green, blue, alpha);
}
public void glColorMask(boolean red, boolean green, boolean blue,
boolean alpha) {
mgl.glColorMask(red, green, blue, alpha);
}
public void glColorPointer(int size, int type, int stride, Buffer pointer) {
mgl.glColorPointer(size, type, stride, pointer);
}
public void glCompressedTexImage2D(int target, int level,
int internalformat, int width, int height, int border,
int imageSize, Buffer data) {
mgl.glCompressedTexImage2D(target, level, internalformat, width,
height, border, imageSize, data);
}
public void glCompressedTexSubImage2D(int target, int level, int xoffset,
int yoffset, int width, int height, int format, int imageSize,
Buffer data) {
mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width,
height, format, imageSize, data);
}
public void glCopyTexImage2D(int target, int level, int internalformat,
int x, int y, int width, int height, int border) {
mgl.glCopyTexImage2D(target, level, internalformat, x, y, width,
height, border);
}
public void glCopyTexSubImage2D(int target, int level, int xoffset,
int yoffset, int x, int y, int width, int height) {
mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width,
height);
}
public void glCullFace(int mode) {
mgl.glCullFace(mode);
}
public void glDeleteTextures(int n, int[] textures, int offset) {
mgl.glDeleteTextures(n, textures, offset);
}
public void glDeleteTextures(int n, IntBuffer textures) {
mgl.glDeleteTextures(n, textures);
}
public void glDepthFunc(int func) {
mgl.glDepthFunc(func);
}
public void glDepthMask(boolean flag) {
mgl.glDepthMask(flag);
}
public void glDepthRangef(float near, float far) {
mgl.glDepthRangef(near, far);
}
public void glDepthRangex(int near, int far) {
mgl.glDepthRangex(near, far);
}
public void glDisable(int cap) {
mgl.glDisable(cap);
}
public void glDisableClientState(int array) {
mgl.glDisableClientState(array);
}
public void glDrawArrays(int mode, int first, int count) {
mgl.glDrawArrays(mode, first, count);
}
public void glDrawElements(int mode, int count, int type, Buffer indices) {
mgl.glDrawElements(mode, count, type, indices);
}
public void glEnable(int cap) {
mgl.glEnable(cap);
}
public void glEnableClientState(int array) {
mgl.glEnableClientState(array);
}
public void glFinish() {
mgl.glFinish();
}
public void glFlush() {
mgl.glFlush();
}
public void glFogf(int pname, float param) {
mgl.glFogf(pname, param);
}
public void glFogfv(int pname, float[] params, int offset) {
mgl.glFogfv(pname, params, offset);
}
public void glFogfv(int pname, FloatBuffer params) {
mgl.glFogfv(pname, params);
}
public void glFogx(int pname, int param) {
mgl.glFogx(pname, param);
}
public void glFogxv(int pname, int[] params, int offset) {
mgl.glFogxv(pname, params, offset);
}
public void glFogxv(int pname, IntBuffer params) {
mgl.glFogxv(pname, params);
}
public void glFrontFace(int mode) {
mgl.glFrontFace(mode);
}
public void glFrustumf(float left, float right, float bottom, float top,
float near, float far) {
mCurrent.glFrustumf(left, right, bottom, top, near, far);
mgl.glFrustumf(left, right, bottom, top, near, far);
if ( _check) check();
}
public void glFrustumx(int left, int right, int bottom, int top, int near,
int far) {
mCurrent.glFrustumx(left, right, bottom, top, near, far);
mgl.glFrustumx(left, right, bottom, top, near, far);
if ( _check) check();
}
public void glGenTextures(int n, int[] textures, int offset) {
mgl.glGenTextures(n, textures, offset);
}
public void glGenTextures(int n, IntBuffer textures) {
mgl.glGenTextures(n, textures);
}
public int glGetError() {
int result = mgl.glGetError();
return result;
}
public void glGetIntegerv(int pname, int[] params, int offset) {
mgl.glGetIntegerv(pname, params, offset);
}
public void glGetIntegerv(int pname, IntBuffer params) {
mgl.glGetIntegerv(pname, params);
}
public String glGetString(int name) {
String result = mgl.glGetString(name);
return result;
}
public void glHint(int target, int mode) {
mgl.glHint(target, mode);
}
public void glLightModelf(int pname, float param) {
mgl.glLightModelf(pname, param);
}
public void glLightModelfv(int pname, float[] params, int offset) {
mgl.glLightModelfv(pname, params, offset);
}
public void glLightModelfv(int pname, FloatBuffer params) {
mgl.glLightModelfv(pname, params);
}
public void glLightModelx(int pname, int param) {
mgl.glLightModelx(pname, param);
}
public void glLightModelxv(int pname, int[] params, int offset) {
mgl.glLightModelxv(pname, params, offset);
}
public void glLightModelxv(int pname, IntBuffer params) {
mgl.glLightModelxv(pname, params);
}
public void glLightf(int light, int pname, float param) {
mgl.glLightf(light, pname, param);
}
public void glLightfv(int light, int pname, float[] params, int offset) {
mgl.glLightfv(light, pname, params, offset);
}
public void glLightfv(int light, int pname, FloatBuffer params) {
mgl.glLightfv(light, pname, params);
}
public void glLightx(int light, int pname, int param) {
mgl.glLightx(light, pname, param);
}
public void glLightxv(int light, int pname, int[] params, int offset) {
mgl.glLightxv(light, pname, params, offset);
}
public void glLightxv(int light, int pname, IntBuffer params) {
mgl.glLightxv(light, pname, params);
}
public void glLineWidth(float width) {
mgl.glLineWidth(width);
}
public void glLineWidthx(int width) {
mgl.glLineWidthx(width);
}
public void glLoadIdentity() {
mCurrent.glLoadIdentity();
mgl.glLoadIdentity();
if ( _check) check();
}
public void glLoadMatrixf(float[] m, int offset) {
mCurrent.glLoadMatrixf(m, offset);
mgl.glLoadMatrixf(m, offset);
if ( _check) check();
}
public void glLoadMatrixf(FloatBuffer m) {
int position = m.position();
mCurrent.glLoadMatrixf(m);
m.position(position);
mgl.glLoadMatrixf(m);
if ( _check) check();
}
public void glLoadMatrixx(int[] m, int offset) {
mCurrent.glLoadMatrixx(m, offset);
mgl.glLoadMatrixx(m, offset);
if ( _check) check();
}
public void glLoadMatrixx(IntBuffer m) {
int position = m.position();
mCurrent.glLoadMatrixx(m);
m.position(position);
mgl.glLoadMatrixx(m);
if ( _check) check();
}
public void glLogicOp(int opcode) {
mgl.glLogicOp(opcode);
}
public void glMaterialf(int face, int pname, float param) {
mgl.glMaterialf(face, pname, param);
}
public void glMaterialfv(int face, int pname, float[] params, int offset) {
mgl.glMaterialfv(face, pname, params, offset);
}
public void glMaterialfv(int face, int pname, FloatBuffer params) {
mgl.glMaterialfv(face, pname, params);
}
public void glMaterialx(int face, int pname, int param) {
mgl.glMaterialx(face, pname, param);
}
public void glMaterialxv(int face, int pname, int[] params, int offset) {
mgl.glMaterialxv(face, pname, params, offset);
}
public void glMaterialxv(int face, int pname, IntBuffer params) {
mgl.glMaterialxv(face, pname, params);
}
public void glMatrixMode(int mode) {
switch (mode) {
case GL10.GL_MODELVIEW:
mCurrent = mModelView;
break;
case GL10.GL_TEXTURE:
mCurrent = mTexture;
break;
case GL10.GL_PROJECTION:
mCurrent = mProjection;
break;
default:
throw new IllegalArgumentException("Unknown matrix mode: " + mode);
}
mgl.glMatrixMode(mode);
mMatrixMode = mode;
if ( _check) check();
}
public void glMultMatrixf(float[] m, int offset) {
mCurrent.glMultMatrixf(m, offset);
mgl.glMultMatrixf(m, offset);
if ( _check) check();
}
public void glMultMatrixf(FloatBuffer m) {
int position = m.position();
mCurrent.glMultMatrixf(m);
m.position(position);
mgl.glMultMatrixf(m);
if ( _check) check();
}
public void glMultMatrixx(int[] m, int offset) {
mCurrent.glMultMatrixx(m, offset);
mgl.glMultMatrixx(m, offset);
if ( _check) check();
}
public void glMultMatrixx(IntBuffer m) {
int position = m.position();
mCurrent.glMultMatrixx(m);
m.position(position);
mgl.glMultMatrixx(m);
if ( _check) check();
}
public void glMultiTexCoord4f(int target,
float s, float t, float r, float q) {
mgl.glMultiTexCoord4f(target, s, t, r, q);
}
public void glMultiTexCoord4x(int target, int s, int t, int r, int q) {
mgl.glMultiTexCoord4x(target, s, t, r, q);
}
public void glNormal3f(float nx, float ny, float nz) {
mgl.glNormal3f(nx, ny, nz);
}
public void glNormal3x(int nx, int ny, int nz) {
mgl.glNormal3x(nx, ny, nz);
}
public void glNormalPointer(int type, int stride, Buffer pointer) {
mgl.glNormalPointer(type, stride, pointer);
}
public void glOrthof(float left, float right, float bottom, float top,
float near, float far) {
mCurrent.glOrthof(left, right, bottom, top, near, far);
mgl.glOrthof(left, right, bottom, top, near, far);
if ( _check) check();
}
public void glOrthox(int left, int right, int bottom, int top, int near,
int far) {
mCurrent.glOrthox(left, right, bottom, top, near, far);
mgl.glOrthox(left, right, bottom, top, near, far);
if ( _check) check();
}
public void glPixelStorei(int pname, int param) {
mgl.glPixelStorei(pname, param);
}
public void glPointSize(float size) {
mgl.glPointSize(size);
}
public void glPointSizex(int size) {
mgl.glPointSizex(size);
}
public void glPolygonOffset(float factor, float units) {
mgl.glPolygonOffset(factor, units);
}
public void glPolygonOffsetx(int factor, int units) {
mgl.glPolygonOffsetx(factor, units);
}
public void glPopMatrix() {
mCurrent.glPopMatrix();
mgl.glPopMatrix();
if ( _check) check();
}
public void glPushMatrix() {
mCurrent.glPushMatrix();
mgl.glPushMatrix();
if ( _check) check();
}
public void glReadPixels(int x, int y, int width, int height, int format,
int type, Buffer pixels) {
mgl.glReadPixels(x, y, width, height, format, type, pixels);
}
public void glRotatef(float angle, float x, float y, float z) {
mCurrent.glRotatef(angle, x, y, z);
mgl.glRotatef(angle, x, y, z);
if ( _check) check();
}
public void glRotatex(int angle, int x, int y, int z) {
mCurrent.glRotatex(angle, x, y, z);
mgl.glRotatex(angle, x, y, z);
if ( _check) check();
}
public void glSampleCoverage(float value, boolean invert) {
mgl.glSampleCoverage(value, invert);
}
public void glSampleCoveragex(int value, boolean invert) {
mgl.glSampleCoveragex(value, invert);
}
public void glScalef(float x, float y, float z) {
mCurrent.glScalef(x, y, z);
mgl.glScalef(x, y, z);
if ( _check) check();
}
public void glScalex(int x, int y, int z) {
mCurrent.glScalex(x, y, z);
mgl.glScalex(x, y, z);
if ( _check) check();
}
public void glScissor(int x, int y, int width, int height) {
mgl.glScissor(x, y, width, height);
}
public void glShadeModel(int mode) {
mgl.glShadeModel(mode);
}
public void glStencilFunc(int func, int ref, int mask) {
mgl.glStencilFunc(func, ref, mask);
}
public void glStencilMask(int mask) {
mgl.glStencilMask(mask);
}
public void glStencilOp(int fail, int zfail, int zpass) {
mgl.glStencilOp(fail, zfail, zpass);
}
public void glTexCoordPointer(int size, int type,
int stride, Buffer pointer) {
mgl.glTexCoordPointer(size, type, stride, pointer);
}
public void glTexEnvf(int target, int pname, float param) {
mgl.glTexEnvf(target, pname, param);
}
public void glTexEnvfv(int target, int pname, float[] params, int offset) {
mgl.glTexEnvfv(target, pname, params, offset);
}
public void glTexEnvfv(int target, int pname, FloatBuffer params) {
mgl.glTexEnvfv(target, pname, params);
}
public void glTexEnvx(int target, int pname, int param) {
mgl.glTexEnvx(target, pname, param);
}
public void glTexEnvxv(int target, int pname, int[] params, int offset) {
mgl.glTexEnvxv(target, pname, params, offset);
}
public void glTexEnvxv(int target, int pname, IntBuffer params) {
mgl.glTexEnvxv(target, pname, params);
}
public void glTexImage2D(int target, int level, int internalformat,
int width, int height, int border, int format, int type,
Buffer pixels) {
mgl.glTexImage2D(target, level, internalformat, width, height, border,
format, type, pixels);
}
public void glTexParameterf(int target, int pname, float param) {
mgl.glTexParameterf(target, pname, param);
}
public void glTexParameterx(int target, int pname, int param) {
mgl.glTexParameterx(target, pname, param);
}
public void glTexParameteriv(int target, int pname, int[] params, int offset) {
mgl11.glTexParameteriv(target, pname, params, offset);
}
public void glTexParameteriv(int target, int pname, IntBuffer params) {
mgl11.glTexParameteriv(target, pname, params);
}
public void glTexSubImage2D(int target, int level, int xoffset,
int yoffset, int width, int height, int format, int type,
Buffer pixels) {
mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height,
format, type, pixels);
}
public void glTranslatef(float x, float y, float z) {
mCurrent.glTranslatef(x, y, z);
mgl.glTranslatef(x, y, z);
if ( _check) check();
}
public void glTranslatex(int x, int y, int z) {
mCurrent.glTranslatex(x, y, z);
mgl.glTranslatex(x, y, z);
if ( _check) check();
}
public void glVertexPointer(int size, int type,
int stride, Buffer pointer) {
mgl.glVertexPointer(size, type, stride, pointer);
}
public void glViewport(int x, int y, int width, int height) {
mgl.glViewport(x, y, width, height);
}
public void glClipPlanef(int plane, float[] equation, int offset) {
mgl11.glClipPlanef(plane, equation, offset);
}
public void glClipPlanef(int plane, FloatBuffer equation) {
mgl11.glClipPlanef(plane, equation);
}
public void glClipPlanex(int plane, int[] equation, int offset) {
mgl11.glClipPlanex(plane, equation, offset);
}
public void glClipPlanex(int plane, IntBuffer equation) {
mgl11.glClipPlanex(plane, equation);
}
// Draw Texture Extension
public void glDrawTexfOES(float x, float y, float z,
float width, float height) {
mgl11Ext.glDrawTexfOES(x, y, z, width, height);
}
public void glDrawTexfvOES(float[] coords, int offset) {
mgl11Ext.glDrawTexfvOES(coords, offset);
}
public void glDrawTexfvOES(FloatBuffer coords) {
mgl11Ext.glDrawTexfvOES(coords);
}
public void glDrawTexiOES(int x, int y, int z, int width, int height) {
mgl11Ext.glDrawTexiOES(x, y, z, width, height);
}
public void glDrawTexivOES(int[] coords, int offset) {
mgl11Ext.glDrawTexivOES(coords, offset);
}
public void glDrawTexivOES(IntBuffer coords) {
mgl11Ext.glDrawTexivOES(coords);
}
public void glDrawTexsOES(short x, short y, short z,
short width, short height) {
mgl11Ext.glDrawTexsOES(x, y, z, width, height);
}
public void glDrawTexsvOES(short[] coords, int offset) {
mgl11Ext.glDrawTexsvOES(coords, offset);
}
public void glDrawTexsvOES(ShortBuffer coords) {
mgl11Ext.glDrawTexsvOES(coords);
}
public void glDrawTexxOES(int x, int y, int z, int width, int height) {
mgl11Ext.glDrawTexxOES(x, y, z, width, height);
}
public void glDrawTexxvOES(int[] coords, int offset) {
mgl11Ext.glDrawTexxvOES(coords, offset);
}
public void glDrawTexxvOES(IntBuffer coords) {
mgl11Ext.glDrawTexxvOES(coords);
}
public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset,
int[] exponent, int exponentOffset) {
return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset,
exponent, exponentOffset);
}
public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) {
return mgl10Ext.glQueryMatrixxOES(mantissa, exponent);
}
// Unsupported GL11 methods
public void glBindBuffer(int target, int buffer) {
throw new UnsupportedOperationException();
}
public void glBufferData(int target, int size, Buffer data, int usage) {
throw new UnsupportedOperationException();
}
public void glBufferSubData(int target, int offset, int size, Buffer data) {
throw new UnsupportedOperationException();
}
public void glColor4ub(byte red, byte green, byte blue, byte alpha) {
throw new UnsupportedOperationException();
}
public void glDeleteBuffers(int n, int[] buffers, int offset) {
throw new UnsupportedOperationException();
}
public void glDeleteBuffers(int n, IntBuffer buffers) {
throw new UnsupportedOperationException();
}
public void glGenBuffers(int n, int[] buffers, int offset) {
throw new UnsupportedOperationException();
}
public void glGenBuffers(int n, IntBuffer buffers) {
throw new UnsupportedOperationException();
}
public void glGetBooleanv(int pname, boolean[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetBooleanv(int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetBufferParameteriv(int target, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetClipPlanef(int pname, float[] eqn, int offset) {
throw new UnsupportedOperationException();
}
public void glGetClipPlanef(int pname, FloatBuffer eqn) {
throw new UnsupportedOperationException();
}
public void glGetClipPlanex(int pname, int[] eqn, int offset) {
throw new UnsupportedOperationException();
}
public void glGetClipPlanex(int pname, IntBuffer eqn) {
throw new UnsupportedOperationException();
}
public void glGetFixedv(int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetFixedv(int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetFloatv(int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetFloatv(int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetLightfv(int light, int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetLightfv(int light, int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetLightxv(int light, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetLightxv(int light, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetMaterialfv(int face, int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetMaterialfv(int face, int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetMaterialxv(int face, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetMaterialxv(int face, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetTexEnviv(int env, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetTexEnviv(int env, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetTexEnvxv(int env, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetTexEnvxv(int env, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetTexParameterfv(int target, int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetTexParameterfv(int target, int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetTexParameteriv(int target, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetTexParameteriv(int target, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glGetTexParameterxv(int target, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glGetTexParameterxv(int target, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public boolean glIsBuffer(int buffer) {
throw new UnsupportedOperationException();
}
public boolean glIsEnabled(int cap) {
throw new UnsupportedOperationException();
}
public boolean glIsTexture(int texture) {
throw new UnsupportedOperationException();
}
public void glPointParameterf(int pname, float param) {
throw new UnsupportedOperationException();
}
public void glPointParameterfv(int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glPointParameterfv(int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glPointParameterx(int pname, int param) {
throw new UnsupportedOperationException();
}
public void glPointParameterxv(int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glPointParameterxv(int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glPointSizePointerOES(int type, int stride, Buffer pointer) {
throw new UnsupportedOperationException();
}
public void glTexEnvi(int target, int pname, int param) {
throw new UnsupportedOperationException();
}
public void glTexEnviv(int target, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glTexEnviv(int target, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glTexParameterfv(int target, int pname, float[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glTexParameterfv(int target, int pname, FloatBuffer params) {
throw new UnsupportedOperationException();
}
public void glTexParameteri(int target, int pname, int param) {
throw new UnsupportedOperationException();
}
public void glTexParameterxv(int target, int pname, int[] params, int offset) {
throw new UnsupportedOperationException();
}
public void glTexParameterxv(int target, int pname, IntBuffer params) {
throw new UnsupportedOperationException();
}
public void glColorPointer(int size, int type, int stride, int offset) {
throw new UnsupportedOperationException();
}
public void glDrawElements(int mode, int count, int type, int offset) {
throw new UnsupportedOperationException();
}
public void glGetPointerv(int pname, Buffer[] params) {
throw new UnsupportedOperationException();
}
public void glNormalPointer(int type, int stride, int offset) {
throw new UnsupportedOperationException();
}
public void glTexCoordPointer(int size, int type, int stride, int offset) {
throw new UnsupportedOperationException();
}
public void glVertexPointer(int size, int type, int stride, int offset) {
throw new UnsupportedOperationException();
}
public void glCurrentPaletteMatrixOES(int matrixpaletteindex) {
throw new UnsupportedOperationException();
}
public void glLoadPaletteFromModelViewMatrixOES() {
throw new UnsupportedOperationException();
}
public void glMatrixIndexPointerOES(int size, int type, int stride,
Buffer pointer) {
throw new UnsupportedOperationException();
}
public void glMatrixIndexPointerOES(int size, int type, int stride,
int offset) {
throw new UnsupportedOperationException();
}
public void glWeightPointerOES(int size, int type, int stride,
Buffer pointer) {
throw new UnsupportedOperationException();
}
public void glWeightPointerOES(int size, int type, int stride, int offset) {
throw new UnsupportedOperationException();
}
/**
* Get the current matrix
*/
public void getMatrix(float[] m, int offset) {
mCurrent.getMatrix(m, offset);
}
/**
* Get the current matrix mode
*/
public int getMatrixMode() {
return mMatrixMode;
}
private void check() {
int oesMode;
switch (mMatrixMode) {
case GL_MODELVIEW:
oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES;
break;
case GL_PROJECTION:
oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES;
break;
case GL_TEXTURE:
oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES;
break;
default:
throw new IllegalArgumentException("Unknown matrix mode");
}
if ( mByteBuffer == null) {
mCheckA = new float[16];
mCheckB = new float[16];
mByteBuffer = ByteBuffer.allocateDirect(64);
mByteBuffer.order(ByteOrder.nativeOrder());
mFloatBuffer = mByteBuffer.asFloatBuffer();
}
mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer());
for(int i = 0; i < 16; i++) {
mCheckB[i] = mFloatBuffer.get(i);
}
mCurrent.getMatrix(mCheckA, 0);
boolean fail = false;
for(int i = 0; i < 16; i++) {
if (mCheckA[i] != mCheckB[i]) {
Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i]
+ " a:" + mCheckB[i]);
fail = true;
}
}
if (fail) {
throw new IllegalArgumentException("Matrix math difference.");
}
}
}
| Java |
/*
* Copyright (C) 2008 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.opengles.spritetext;
import javax.microedition.khronos.opengles.GL;
import android.app.Activity;
import android.os.Bundle;
public class SpriteTextActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGLView = (GLView) findViewById(R.id.glview);
mGLView.setGLWrapper(new GLView.GLWrapper() {
public GL wrap(GL gl) {
return new MatrixTrackingGL(gl);
}});
mGLView.setRenderer(new SpriteTextRenderer(this));
mGLView.requestFocus();
}
@Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
private GLView mGLView;
}
| Java |
/*
* Copyright (C) 2007 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.opengles.spritetext;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import javax.microedition.khronos.opengles.GL10;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
*
*/
class Grid {
public Grid(int w, int h) {
if (w < 0 || w >= 65536) {
throw new IllegalArgumentException("w");
}
if (h < 0 || h >= 65536) {
throw new IllegalArgumentException("h");
}
if (w * h >= 65536) {
throw new IllegalArgumentException("w * h >= 65536");
}
mW = w;
mH = h;
int size = w * h;
mVertexArray = new float[size * 3];
mVertexBuffer = FloatBuffer.wrap(mVertexArray);
mTexCoordArray = new float[size * 2];
mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray);
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
char[] indexArray = new char[indexCount];
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
indexArray[i++] = a;
indexArray[i++] = b;
indexArray[i++] = c;
indexArray[i++] = b;
indexArray[i++] = c;
indexArray[i++] = d;
}
}
}
mIndexBuffer = CharBuffer.wrap(indexArray);
}
void set(int i, int j, float x, float y, float z, float u, float v) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
int index = mW * j + i;
int posIndex = index * 3;
mVertexArray[posIndex] = x;
mVertexArray[posIndex + 1] = y;
mVertexArray[posIndex + 2] = z;
int texIndex = index * 2;
mTexCoordArray[texIndex] = u;
mTexCoordArray[texIndex + 1] = v;
}
public void draw(GL10 gl, boolean useTexture) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
private FloatBuffer mVertexBuffer;
private float[] mVertexArray;
private FloatBuffer mTexCoordBuffer;
private float[] mTexCoordArray;
private CharBuffer mIndexBuffer;
private int mW;
private int mH;
private int mIndexCount;
}
| Java |
/*
* Copyright (C) 2008 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.opengles.triangle;
import javax.microedition.khronos.opengles.GL;
import android.app.Activity;
import android.opengl.GLDebugHelper;
import android.os.Bundle;
public class TriangleActivity extends Activity {
/** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to
* false for faster code.
*
*/
private final static boolean DEBUG_CHECK_GL_ERROR = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mGLView = (GLView) findViewById(R.id.glview);
if (DEBUG_CHECK_GL_ERROR) {
mGLView.setGLWrapper(new GLView.GLWrapper() {
public GL wrap(GL gl) {
return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null);
}});
}
mGLView.setRenderer(new TriangleRenderer(this));
mGLView.requestFocus();
}
@Override
protected void onPause() {
super.onPause();
mGLView.onPause();
}
@Override
protected void onResume() {
super.onResume();
mGLView.onResume();
}
private GLView mGLView;
}
| Java |
/*
* Copyright (C) 2008 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.opengles.triangle;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.SystemClock;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
public class TriangleRenderer implements GLView.Renderer{
public TriangleRenderer(Context context) {
mContext = context;
mTriangle = new Triangle();
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_NONE
};
return configSpec;
}
public void surfaceCreated(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
/*
* Some one-time OpenGL initialization can be made here
* probably based on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
GL10.GL_FASTEST);
gl.glClearColor(.5f, .5f, .5f, 1);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* Create our texture. This has to be done each time the
* surface is created.
*/
int[] textures = new int[1];
gl.glGenTextures(1, textures, 0);
mTextureID = textures[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_REPLACE);
InputStream is = mContext.getResources()
.openRawResource(R.drawable.tex);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
} catch(IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
bitmap.recycle();
}
public void drawFrame(GL10 gl) {
/*
* By default, OpenGL enables features that improve quality
* but reduce performance. One might want to tweak that
* especially on software renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
GL10.GL_MODULATE);
/*
* Usually, the first thing one might want to do is to clear
* the screen. The most efficient way of doing this is to use
* glClear().
*/
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
/*
* Now we're ready to draw some 3D objects
*/
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glActiveTexture(GL10.GL_TEXTURE0);
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
GL10.GL_REPEAT);
gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
GL10.GL_REPEAT);
long time = SystemClock.uptimeMillis() % 4000L;
float angle = 0.090f * ((int) time);
gl.glRotatef(angle, 0, 0, 1.0f);
mTriangle.draw(gl);
}
public void sizeChanged(GL10 gl, int w, int h) {
gl.glViewport(0, 0, w, h);
/*
* Set our projection matrix. This doesn't have to be done
* each time we draw, but usually a new projection needs to
* be set when the viewport is resized.
*/
float ratio = (float) w / h;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);
}
private Context mContext;
private Triangle mTriangle;
private int mTextureID;
}
class Triangle {
public Triangle() {
// Buffers to be passed to gl*Pointer() functions
// must be direct, i.e., they must be placed on the
// native heap where the garbage collector cannot
// move them.
//
// Buffers with multi-byte datatypes (e.g., short, int, float)
// must have their byte order set to native order
ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4);
vbb.order(ByteOrder.nativeOrder());
mFVertexBuffer = vbb.asFloatBuffer();
ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4);
tbb.order(ByteOrder.nativeOrder());
mTexBuffer = tbb.asFloatBuffer();
ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2);
ibb.order(ByteOrder.nativeOrder());
mIndexBuffer = ibb.asShortBuffer();
// A unit-sided equalateral triangle centered on the origin.
float[] coords = {
// X, Y, Z
-0.5f, -0.25f, 0,
0.5f, -0.25f, 0,
0.0f, 0.559016994f, 0
};
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 3; j++) {
mFVertexBuffer.put(coords[i*3+j] * 2.0f);
}
}
for (int i = 0; i < VERTS; i++) {
for(int j = 0; j < 2; j++) {
mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f);
}
}
for(int i = 0; i < VERTS; i++) {
mIndexBuffer.put((short) i);
}
mFVertexBuffer.position(0);
mTexBuffer.position(0);
mIndexBuffer.position(0);
}
public void draw(GL10 gl) {
gl.glFrontFace(GL10.GL_CCW);
gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
}
private final static int VERTS = 3;
private FloatBuffer mFVertexBuffer;
private FloatBuffer mTexBuffer;
private ShortBuffer mIndexBuffer;
}
| Java |
/*
* Copyright (C) 2008 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.opengles.triangle;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
class GLView extends SurfaceView implements SurfaceHolder.Callback {
GLView(Context context) {
super(context);
init();
}
public GLView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
mGLThread.queueEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
Runnable r;
while ((r = getEvent()) != null) {
r.run();
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
/* draw a frame here */
mRenderer.drawFrame(gl);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
mEglHelper.swap();
}
}
/*
* clean-up everything...
*/
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void queueEvent(Runnable r) {
synchronized(this) {
mEventQueue.add(r);
}
}
private Runnable getEvent() {
synchronized(this) {
if (mEventQueue.size() > 0) {
return mEventQueue.remove(0);
}
}
return null;
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>();
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
| Java |
package com.google.clickin2dabeat;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
/**
* Checks for updates to the game.
*/
public class UpdateChecker {
public String marketId;
@SuppressWarnings("finally")
public int getLatestVersionCode() {
int version = 0;
try {
URLConnection cn;
URL url =
new URL(
"http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml");
cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document manifestDoc = docBuild.parse(stream);
NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest");
String versionStr =
manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode")
.getNodeValue();
version = Integer.parseInt(versionStr);
NodeList clcNodeList = manifestDoc.getElementsByTagName("clc");
marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return version;
}
}
public void checkForNewerVersion(int currentVersion) {
int latestVersion = getLatestVersionCode();
if (latestVersion > currentVersion) {
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import android.graphics.Color;
/**
* Contains information about the when the beat should be displayed, where it
* should be displayed, and what color it should be.
*/
public class Target {
public double time;
public int x;
public int y;
public int color;
public Target(double timeToHit, int xpos, int ypos, String hexColor) {
time = timeToHit;
x = xpos;
y = ypos;
if (hexColor.length() == 6) {
int r = Integer.parseInt(hexColor.substring(0, 2), 16);
int g = Integer.parseInt(hexColor.substring(2, 4), 16);
int b = Integer.parseInt(hexColor.substring(4, 6), 16);
color = Color.rgb(r, g, b);
} else {
int colorChoice = ((int) (Math.random() * 100)) % 4;
if (colorChoice == 0) {
color = Color.RED;
} else if (colorChoice == 1) {
color = Color.GREEN;
} else if (colorChoice == 2) {
color = Color.BLUE;
} else {
color = Color.YELLOW;
}
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
public class DownloadC2BFile extends Activity {
String dataSource;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
dataSource = this.getIntent().getData().toString();
(new Thread(new loader())).start();
}
public void runMem() {
startApp("com.google.clickin2dabeat", "C2B");
finish();
}
private void startApp(String packageName, String className) {
try {
int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY;
Context myContext = createPackageContext(packageName, flags);
Class<?> appClass = myContext.getClassLoader().loadClass(packageName + "." + className);
Intent intent = new Intent(myContext, appClass);
startActivity(intent);
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public class loader implements Runnable {
public void run() {
Unzipper.unzip(dataSource);
runMem();
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Creates a skeleton C2B file when an appropriate media object is opened.
*/
public class CreateC2BFile extends Activity {
private String dataSource;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
dataSource = this.getIntent().getData().toString();
setContentView(R.layout.c2b_creator_form);
Button create = ((Button) findViewById(R.id.CreateButton));
create.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString();
String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString();
if (!title.equals("") && !author.equals("")) {
createC2BSkeleton(title, author, dataSource);
finish();
}
}
});
Button cancel = ((Button) findViewById(R.id.CancelButton));
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
}
private void createC2BSkeleton(String title, String author, String media) {
String c2bDirStr = "/sdcard/c2b/";
String sanitizedTitle = title.replaceAll("'", " ");
String sanitizedAuthor = author.replaceAll("'", " ");
String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", "");
filename = c2bDirStr + filename + ".c2b";
String contents =
"<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>";
File c2bDir = new File(c2bDirStr);
boolean directoryExists = c2bDir.isDirectory();
if (!directoryExists) {
c2bDir.mkdir();
}
try {
FileWriter writer = new FileWriter(filename);
writer.write(contents);
writer.close();
Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show();
} catch (IOException e) {
Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).show();
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import java.util.ArrayList;
/**
* Adjusts the times for the beat targets using a linear least-squares fit.
*/
public class BeatTimingsAdjuster {
private double[] adjustedBeatTimes;
public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) {
double[] beatTimes = new double[rawBeatTimes.size()];
for (int i = 0; i < beatTimes.length; i++) {
beatTimes[i] = rawBeatTimes.get(i);
}
adjustedBeatTimes = new double[beatTimes.length];
double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double n = beatNumbers.length;
// Some things can be computed once and never computed again
double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers);
double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers);
double sumOfBeatNumbers = sum(beatNumbers);
// The divisor is:
// (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers)))
// Since these are all constants, they can be computed first for better
// efficiency.
double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers)));
// Not enough data to adjust for the first 5 beats
for (int i = 0; (i < beatTimes.length) && (i < 5); i++) {
adjustedBeatTimes[i] = beatTimes[i];
}
// Adjust time for beat i by using timings for beats i-5 through i+5
double[] beatWindow = new double[beatNumbers.length];
for (int i = 0; i < beatTimes.length - 10; i++) {
System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length);
double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow);
double a =
(sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes))
/ divisor;
double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor;
adjustedBeatTimes[i + 5] = a + b * beatNumbers[5];
}
if (beatTimes.length - 10 < 0) {
return;
}
// Not enough data to adjust for the last 5 beats
for (int i = beatTimes.length - 10; i < beatTimes.length; i++) {
adjustedBeatTimes[i] = beatTimes[i];
}
}
public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) {
ArrayList<Target> adjustedTargets = new ArrayList<Target>();
int j = 0;
double threshold = 200;
for (int i = 0; i < rawTargets.size(); i++) {
Target t = rawTargets.get(i);
while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) {
j++;
}
double prevTime = 0;
if (j > 0) {
prevTime = adjustedBeatTimes[j - 1];
}
double postTime = -1;
if (j < adjustedBeatTimes.length) {
postTime = adjustedBeatTimes[j];
}
if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime))
&& Math.abs(t.time - prevTime) < threshold) {
t.time = prevTime;
} else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime))
&& Math.abs(t.time - postTime) < threshold) {
t.time = postTime;
}
adjustedTargets.add(t);
}
return adjustedTargets;
}
private double sum(double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) {
double[] sqArray = new double[numberSetA.length];
for (int i = 0; i < numberSetA.length; i++) {
sqArray[i] = numberSetA[i] * numberSetB[i];
}
return sqArray;
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.VideoView;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
/**
* A rhythm/music game for Android that can use any video as the background.
*/
public class C2B extends Activity {
public static final int GAME_MODE = 0;
public static final int TWOPASS_MODE = 1;
public static final int ONEPASS_MODE = 2;
public int mode;
public boolean wasEditMode;
private boolean forceEditMode;
private VideoView background;
private GameView foreground;
private FrameLayout layout;
private String c2bFileName;
private String[] filenames;
private String marketId;
// These are parsed in from the C2B file
private String title;
private String author;
private String level;
private String media;
private Uri videoUri;
public ArrayList<Target> targets;
public ArrayList<Integer> beatTimes;
private BeatTimingsAdjuster timingAdjuster;
private boolean busyProcessing;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
UpdateChecker checker = new UpdateChecker();
int latestVersion = checker.getLatestVersionCode();
String packageName = C2B.class.getPackage().getName();
int currentVersion = 0;
try {
currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (latestVersion > currentVersion){
marketId = checker.marketId;
displayUpdateMessage();
} else {
resetGame();
}
}
private void resetGame() {
targets = new ArrayList<Target>();
mode = GAME_MODE;
forceEditMode = false;
wasEditMode = false;
busyProcessing = false;
c2bFileName = "";
title = "";
author = "";
level = "";
media = "";
background = null;
foreground = null;
layout = null;
background = new VideoView(this);
foreground = new GameView(this);
layout = new FrameLayout(this);
layout.addView(background);
layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout?
beatTimes = null;
timingAdjuster = null;
background.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
background.start();
}
});
background.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
background.setVideoURI(videoUri);
return true;
}
});
background.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (mode == ONEPASS_MODE) {
Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000);
waitMessage.show();
(new Thread(new BeatsWriter())).start();
} else if (mode == TWOPASS_MODE) {
mode = ONEPASS_MODE;
(new Thread(new BeatsTimingAdjuster())).start();
displayCreateLevelInfo();
return;
}
displayStats();
}
});
layout.addView(foreground);
setContentView(layout);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
displayStartupMessage();
}
private void writeC2BFile(String filename) {
String contents =
"<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media
+ "'>";
ArrayList<Target> targets = foreground.recordedTargets;
if (timingAdjuster != null) {
targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets);
}
for (int i = 0; i < targets.size(); i++) {
Target t = targets.get(i);
contents = contents + "<beat time='" + Double.toString(t.time) + "' ";
contents = contents + "x='" + Integer.toString(t.x) + "' ";
contents = contents + "y='" + Integer.toString(t.y) + "' ";
contents = contents + "color='" + Integer.toHexString(t.color) + "'/>";
}
contents = contents + "</c2b>";
try {
FileWriter writer = new FileWriter(filename);
writer.write(contents);
writer.close();
} catch (IOException e) {
// TODO(clchen): Do better error handling here
e.printStackTrace();
}
}
private void loadC2B(String fileUriString) {
try {
FileInputStream fis = new FileInputStream(fileUriString);
DocumentBuilder docBuild;
docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document c2b = docBuild.parse(fis);
runC2B(c2b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void runC2B(Document c2b) {
Node root = c2b.getElementsByTagName("c2b").item(0);
title = root.getAttributes().getNamedItem("title").getNodeValue();
author = root.getAttributes().getNamedItem("author").getNodeValue();
level = root.getAttributes().getNamedItem("level").getNodeValue();
media = root.getAttributes().getNamedItem("media").getNodeValue();
NodeList beats = c2b.getElementsByTagName("beat");
targets = new ArrayList<Target>();
for (int i = 0; i < beats.getLength(); i++) {
NamedNodeMap attribs = beats.item(i).getAttributes();
double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue());
int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue());
int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue());
String colorStr = attribs.getNamedItem("color").getNodeValue();
targets.add(new Target(time, x, y, colorStr));
}
if ((beats.getLength() == 0) || forceEditMode) {
displayCreateLevelAlert();
} else {
videoUri = Uri.parse(media);
background.setVideoURI(videoUri);
}
}
private void displayCreateLevelAlert() {
mode = ONEPASS_MODE;
Builder createLevelAlert = new Builder(this);
String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\"";
createLevelAlert.setTitle(titleText);
String[] choices = new String[2];
choices[0] = getString(R.string.ONE_PASS);
choices[1] = getString(R.string.TWO_PASS);
createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
mode = ONEPASS_MODE;
} else {
mode = TWOPASS_MODE;
}
}
});
createLevelAlert.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayCreateLevelAlert();
return;
}
wasEditMode = true;
if (mode == TWOPASS_MODE) {
beatTimes = new ArrayList<Integer>();
timingAdjuster = new BeatTimingsAdjuster();
}
displayCreateLevelInfo();
}
});
createLevelAlert.setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayCreateLevelAlert();
return;
}
displayC2BFiles();
}
});
createLevelAlert.setCancelable(false);
createLevelAlert.show();
}
private void displayC2BFiles() {
Builder c2bFilesAlert = new Builder(this);
String titleText = getString(R.string.CHOOSE_STAGE);
c2bFilesAlert.setTitle(titleText);
File c2bDir = new File("/sdcard/c2b/");
filenames = c2bDir.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(".c2b");
}
});
if (filenames == null) {
displayNoFilesMessage();
return;
}
if (filenames.length == 0) {
displayNoFilesMessage();
return;
}
c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
c2bFileName = "/sdcard/c2b/" + filenames[which];
}
});
c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
loadC2B(c2bFileName);
dialog.dismiss();
}
});
/*
c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
displaySetNewBeatsConfirmation();
}
});
*/
final Activity self = this;
c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files");
i.setData(uri);
self.startActivity(i);
finish();
}
});
c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
c2bFilesAlert.setCancelable(false);
c2bFilesAlert.show();
}
/*
private void displaySetNewBeatsConfirmation() {
Builder setNewBeatsConfirmation = new Builder(this);
String titleText = getString(R.string.EDIT_CONFIRMATION);
setNewBeatsConfirmation.setTitle(titleText);
String message = getString(R.string.EDIT_WARNING);
setNewBeatsConfirmation.setMessage(message);
setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
forceEditMode = true;
loadC2B(c2bFileName);
dialog.dismiss();
}
});
setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
displayC2BFiles();
dialog.dismiss();
}
});
setNewBeatsConfirmation.setCancelable(false);
setNewBeatsConfirmation.show();
}
*/
private void displayCreateLevelInfo() {
Builder createLevelInfoAlert = new Builder(this);
String titleText = getString(R.string.BEAT_SETTING_INFO);
createLevelInfoAlert.setTitle(titleText);
String message = "";
if (mode == TWOPASS_MODE) {
message = getString(R.string.TWO_PASS_INFO);
} else {
message = getString(R.string.ONE_PASS_INFO);
}
createLevelInfoAlert.setMessage(message);
createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
videoUri = Uri.parse(media);
background.setVideoURI(videoUri);
}
});
createLevelInfoAlert.setCancelable(false);
createLevelInfoAlert.show();
}
private void displayStats() {
Builder statsAlert = new Builder(this);
String titleText = "";
if (!wasEditMode) {
titleText = "Game Over";
} else {
titleText = "Stage created!";
}
statsAlert.setTitle(titleText);
int longestCombo = foreground.longestCombo;
if (foreground.comboCount > longestCombo) {
longestCombo = foreground.comboCount;
}
String message = "";
if (!wasEditMode) {
message = "Longest combo: " + Integer.toString(longestCombo);
} else {
message = "Beats recorded!";
}
statsAlert.setMessage(message);
statsAlert.setPositiveButton("Play", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayStats();
return;
}
resetGame();
}
});
statsAlert.setNegativeButton("Quit", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayStats();
return;
}
finish();
}
});
statsAlert.setCancelable(false);
statsAlert.show();
}
private void displayNoFilesMessage() {
Builder noFilesMessage = new Builder(this);
String titleText = getString(R.string.NO_STAGES_FOUND);
noFilesMessage.setTitle(titleText);
String message = getString(R.string.NO_STAGES_INFO);
noFilesMessage.setMessage(message);
noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
loadHardCodedRickroll();
}
});
final Activity self = this;
noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files");
i.setData(uri);
self.startActivity(i);
finish();
}
});
noFilesMessage.setNegativeButton(getString(R.string.QUIT),
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
noFilesMessage.setCancelable(false);
noFilesMessage.show();
}
private void loadHardCodedRickroll() {
try {
Resources res = getResources();
InputStream fis = res.openRawResource(R.raw.rickroll);
DocumentBuilder docBuild;
docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document c2b = docBuild.parse(fis);
runC2B(c2b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void displayStartupMessage() {
Builder startupMessage = new Builder(this);
String titleText = getString(R.string.WELCOME);
startupMessage.setTitle(titleText);
String message = getString(R.string.BETA_MESSAGE);
startupMessage.setMessage(message);
startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
displayC2BFiles();
}
});
final Activity self = this;
startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat");
i.setData(uri);
self.startActivity(i);
finish();
}
});
startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
startupMessage.setCancelable(false);
startupMessage.show();
}
private void displayUpdateMessage() {
Builder updateMessage = new Builder(this);
String titleText = getString(R.string.UPDATE_AVAILABLE);
updateMessage.setTitle(titleText);
String message = getString(R.string.UPDATE_MESSAGE);
updateMessage.setMessage(message);
updateMessage.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Uri marketUri = Uri.parse("market://details?id=" + marketId);
Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
startActivity(marketIntent);
finish();
}
});
final Activity self = this;
updateMessage.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
resetGame();
}
});
updateMessage.setCancelable(false);
updateMessage.show();
}
public int getCurrentTime() {
try {
return background.getCurrentPosition();
} catch (IllegalStateException e) {
// This will be thrown if the player is exiting mid-game and the video
// view is going away at the same time as the foreground is trying to get
// the position. This error can be safely ignored without doing anything.
e.printStackTrace();
return 0;
}
}
// Do beats processing in another thread to avoid hogging the UI thread and
// generating a "not responding" error
public class BeatsWriter implements Runnable {
public void run() {
writeC2BFile(c2bFileName);
busyProcessing = false;
}
}
public class BeatsTimingAdjuster implements Runnable {
public void run() {
timingAdjuster.setRawBeatTimes(beatTimes);
busyProcessing = false;
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* Draws the beat targets and takes user input.
* This view is used as the foreground; the background is the video
* being played.
*/
public class GameView extends View {
private static final long[] VIBE_PATTERN = {0, 1, 40, 41};
private static final int INTERVAL = 10; // in ms
private static final int PRE_THRESHOLD = 1000; // in ms
private static final int POST_THRESHOLD = 500; // in ms
private static final int TOLERANCE = 100; // in ms
private static final int POINTS_FOR_PERFECT = 100;
private static final double PENALTY_FACTOR = .25;
private static final double COMBO_FACTOR = .1;
private static final float TARGET_RADIUS = 50;
public static final String LAST_RATING_OK = "(^_')";
public static final String LAST_RATING_PERFECT = "(^_^)/";
public static final String LAST_RATING_MISS = "(X_X)";
private C2B parent;
private Vibrator vibe;
private SoundPool snd;
private int hitOkSfx;
private int hitPerfectSfx;
private int missSfx;
public int comboCount;
public int longestCombo;
public String lastRating;
Paint innerPaint;
Paint borderPaint;
Paint haloPaint;
private ArrayList<Target> drawnTargets;
private int lastTarget;
public ArrayList<Target> recordedTargets;
private int score;
public GameView(Context context) {
super(context);
parent = (C2B) context;
lastTarget = 0;
score = 0;
comboCount = 0;
longestCombo = 0;
lastRating = "";
drawnTargets = new ArrayList<Target>();
recordedTargets = new ArrayList<Target>();
vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0);
missSfx = snd.load(context, R.raw.miss, 0);
hitOkSfx = snd.load(context, R.raw.ok, 0);
hitPerfectSfx = snd.load(context, R.raw.perfect, 0);
innerPaint = new Paint();
innerPaint.setColor(Color.argb(127, 0, 0, 0));
innerPaint.setStyle(Paint.Style.FILL);
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
borderPaint.setStrokeWidth(2);
haloPaint = new Paint();
haloPaint.setStyle(Paint.Style.STROKE);
haloPaint.setAntiAlias(true);
haloPaint.setStrokeWidth(4);
Thread monitorThread = (new Thread(new Monitor()));
monitorThread.setPriority(Thread.MIN_PRIORITY);
monitorThread.start();
}
private void updateTargets() {
int i = lastTarget;
int currentTime = parent.getCurrentTime();
// Add any targets that are within the pre-threshold to the list of
// drawnTargets
boolean cont = true;
while (cont && (i < parent.targets.size())) {
if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) {
drawnTargets.add(parent.targets.get(i));
i++;
} else {
cont = false;
}
}
lastTarget = i;
// Move any expired targets out of drawn targets
for (int j = 0; j < drawnTargets.size(); j++) {
Target t = drawnTargets.get(j);
if (t == null) {
// Do nothing - this is a concurrency issue where
// the target is already gone, so just ignore it
} else if (t.time + POST_THRESHOLD < currentTime) {
try {
drawnTargets.remove(j);
} catch (IndexOutOfBoundsException e){
// Do nothing here, j is already gone
}
if (longestCombo < comboCount) {
longestCombo = comboCount;
}
comboCount = 0;
lastRating = LAST_RATING_MISS;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int currentTime = parent.getCurrentTime();
float x = event.getX();
float y = event.getY();
boolean hadHit = false;
if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target
hadHit = true;
snd.play(hitPerfectSfx, 1, 1, 0, 0, 1);
Target targ = new Target(currentTime, (int) x, (int) y, "");
recordedTargets.add(targ);
} else if (parent.mode == C2B.TWOPASS_MODE) {
hadHit = true;
parent.beatTimes.add(currentTime);
} else { // Play the game normally
for (int i = 0; i < drawnTargets.size(); i++) {
if (hitTarget(x, y, drawnTargets.get(i))) {
Target t = drawnTargets.get(i);
int points;
double timeDiff = Math.abs(currentTime - t.time);
if (timeDiff < TOLERANCE) {
points = POINTS_FOR_PERFECT;
snd.play(hitPerfectSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_PERFECT;
} else {
points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR));
points = points + (int) (points * (comboCount * COMBO_FACTOR));
snd.play(hitOkSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_OK;
}
if (points > 0) {
score = score + points;
hadHit = true;
}
drawnTargets.remove(i);
break;
}
}
}
if (hadHit) {
comboCount++;
} else {
if (longestCombo < comboCount) {
longestCombo = comboCount;
}
comboCount = 0;
snd.play(missSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_MISS;
}
vibe.vibrate(VIBE_PATTERN, -1);
}
return true;
}
private boolean hitTarget(float x, float y, Target t) {
if (t == null) {
return false;
}
// Use the pythagorean theorem to solve this.
float xSquared = (t.x - x) * (t.x - x);
float ySquared = (t.y - y) * (t.y - y);
if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) {
return true;
}
return false;
}
@Override
public void onDraw(Canvas canvas) {
if (parent.mode != C2B.GAME_MODE) {
return;
}
int currentTime = parent.getCurrentTime();
// Draw the circles
for (int i = 0; i < drawnTargets.size(); i++) {
Target t = drawnTargets.get(i);
if (t == null) {
break;
}
// Insides should be semi-transparent
canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint);
// Set colors for the target
borderPaint.setColor(t.color);
haloPaint.setColor(t.color);
// Perfect timing == hitting the halo inside the borders
canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint);
canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint);
// Draw timing halos - may need to change the formula here
float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD;
int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS));
canvas.drawCircle(t.x, t.y, haloSize, haloPaint);
}
// Score and Combo info
String scoreText = "Score: " + Integer.toString(score);
int x = getWidth() - 100; // Fudge factor for making it on the top right
// corner
int y = 30;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(24);
paint.setTypeface(Typeface.DEFAULT_BOLD);
y -= paint.ascent() / 2;
canvas.drawText(scoreText, x, y, paint);
x = getWidth() / 2;
canvas.drawText(lastRating, x, y, paint);
String comboText = "Combo: " + Integer.toString(comboCount);
x = 60;
canvas.drawText(comboText, x, y, paint);
}
private class Monitor implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
// This should not be interrupted. If it is, just dump the stack
// trace.
e.printStackTrace();
}
updateTargets();
postInvalidate();
}
}
}
}
| Java |
/*
* Copyright (C) 2008 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.clickin2dabeat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipFile;
public class Unzipper {
public static String download(String fileUrl) {
URLConnection cn;
try {
fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString();
URL url = new URL(fileUrl);
cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
File outputDir = new File("/sdcard/c2b/");
outputDir.mkdirs();
String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
filename = filename.substring(0, filename.indexOf("c2b.zip") + 7);
File outputFile = new File("/sdcard/c2b/", filename);
outputFile.createNewFile();
FileOutputStream out = new FileOutputStream(outputFile);
byte buf[] = new byte[16384];
do {
int numread = stream.read(buf);
if (numread <= 0) {
break;
} else {
out.write(buf, 0, numread);
}
} while (true);
stream.close();
out.close();
return "/sdcard/c2b/" + filename;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
public static void unzip(String fileUrl) {
try {
String filename = download(fileUrl);
ZipFile zip = new ZipFile(filename);
Enumeration<? extends ZipEntry> zippedFiles = zip.entries();
while (zippedFiles.hasMoreElements()) {
ZipEntry entry = zippedFiles.nextElement();
InputStream is = zip.getInputStream(entry);
String name = entry.getName();
File outputFile = new File("/sdcard/c2b/" + name);
String outputPath = outputFile.getCanonicalPath();
name = outputPath.substring(outputPath.lastIndexOf("/") + 1);
outputPath = outputPath.substring(0, outputPath.lastIndexOf("/"));
File outputDir = new File(outputPath);
outputDir.mkdirs();
outputFile = new File(outputPath, name);
outputFile.createNewFile();
FileOutputStream out = new FileOutputStream(outputFile);
byte buf[] = new byte[16384];
do {
int numread = is.read(buf);
if (numread <= 0) {
break;
} else {
out.write(buf, 0, numread);
}
} while (true);
is.close();
out.close();
}
File theZipFile = new File(filename);
theZipFile.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
public class Sphere extends Shape {
public Sphere(boolean emitTextureCoordinates,
boolean emitNormals, boolean emitColors) {
super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT,
emitTextureCoordinates, emitNormals, emitColors);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
/**
* A class representing a city, with an associated position, time zone name,
* and raw offset from UTC.
*/
public class City implements Comparable<City> {
private static Map<String,City> cities = new HashMap<String,City>();
private static City[] citiesByRawOffset;
private String name;
private String timeZoneID;
private TimeZone timeZone = null;
private int rawOffset;
private float latitude, longitude;
private float x, y, z;
/**
* Loads the city database. The cities must be stored in order by raw
* offset from UTC.
*/
public static void loadCities(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
int numCities = dis.readInt();
citiesByRawOffset = new City[numCities];
byte[] buf = new byte[24];
for (int i = 0; i < numCities; i++) {
String name = dis.readUTF();
String tzid = dis.readUTF();
dis.read(buf);
// The code below is a faster version of:
// int rawOffset = dis.readInt();
// float latitude = dis.readFloat();
// float longitude = dis.readFloat();
// float cx = dis.readFloat();
// float cy = dis.readFloat();
// float cz = dis.readFloat();
int rawOffset =
(buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) |
((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff);
int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) |
((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff);
int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) |
((buf[10] & 0xff) << 8) | (buf[11] & 0xff);
int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) |
((buf[14] & 0xff) << 8) | (buf[15] & 0xff);
int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) |
((buf[18] & 0xff) << 8) | (buf[19] & 0xff);
int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) |
((buf[22] & 0xff) << 8) | (buf[23] & 0xff);
float latitude = Float.intBitsToFloat(ilat);
float longitude = Float.intBitsToFloat(ilon);
float cx = Float.intBitsToFloat(icx);
float cy = Float.intBitsToFloat(icy);
float cz = Float.intBitsToFloat(icz);
City city = new City(name, tzid, rawOffset,
latitude, longitude, cx, cy, cz);
cities.put(name, city);
citiesByRawOffset[i] = city;
}
}
/**
* Returns the cities, ordered by name.
*/
public static City[] getCitiesByName() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities);
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This requires reading the entire time zone database
* behind the scenes.
*/
public static City[] getCitiesByOffset() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities, new Comparator<City>() {
public int compare(City c1, City c2) {
long now = System.currentTimeMillis();
TimeZone tz1 = c1.getTimeZone();
TimeZone tz2 = c2.getTimeZone();
int off1 = tz1.getOffset(now);
int off2 = tz2.getOffset(now);
if (off1 == off2) {
float dlat = c2.getLatitude() - c1.getLatitude();
if (dlat < 0.0f) return -1;
if (dlat > 0.0f) return 1;
return 0;
}
return off1 - off2;
}
});
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This does not require reading the time zone database
* since the cities are pre-sorted.
*/
public static City[] getCitiesByRawOffset() {
return citiesByRawOffset;
}
/**
* Returns an Iterator over all cities, in raw offset order.
*/
public static Iterator<City> iterator() {
return cities.values().iterator();
}
/**
* Returns the total number of cities.
*/
public static int numCities() {
return cities.size();
}
/**
* Constructs a city with the given name, time zone name, raw offset,
* latitude, longitude, and 3D (X, Y, Z) coordinate.
*/
public City(String name, String timeZoneID,
int rawOffset,
float latitude, float longitude,
float x, float y, float z) {
this.name = name;
this.timeZoneID = timeZoneID;
this.rawOffset = rawOffset;
this.latitude = latitude;
this.longitude = longitude;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() {
return name;
}
public TimeZone getTimeZone() {
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone;
}
public float getLongitude() {
return longitude;
}
public float getLatitude() {
return latitude;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRawOffset() {
return rawOffset / 3600000.0f;
}
public int getRawOffsetMillis() {
return rawOffset;
}
/**
* Returns this city's offset from UTC, taking summer/daylight savigns
* time into account.
*/
public float getOffset() {
long now = System.currentTimeMillis();
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone.getOffset(now) / 3600000.0f;
}
/**
* Compares this city to another by name.
*/
public int compareTo(City o) {
return name.compareTo(o.name);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.text.DateFormat;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.text.format.DateUtils;
//import android.text.format.DateFormat;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
/**
* A class that draws an analog clock face with information about the current
* time in a given city.
*/
public class Clock {
static final int MILLISECONDS_PER_MINUTE = 60 * 1000;
static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000;
private City mCity = null;
private long mCitySwitchTime;
private long mTime;
private float mColorRed = 1.0f;
private float mColorGreen = 1.0f;
private float mColorBlue = 1.0f;
private long mOldOffset;
private Interpolator mClockHandInterpolator =
new AccelerateDecelerateInterpolator();
public Clock() {
// Empty constructor
}
/**
* Adds a line to the given Path. The line extends from
* radius r0 to radius r1 about the center point (cx, cy),
* at an angle given by pos.
*
* @param path the Path to draw to
* @param radius the radius of the outer rim of the clock
* @param pos the angle, with 0 and 1 at 12:00
* @param cx the X coordinate of the clock center
* @param cy the Y coordinate of the clock center
* @param r0 the starting radius for the line
* @param r1 the ending radius for the line
*/
private static void drawLine(Path path,
float radius, float pos, float cx, float cy, float r0, float r1) {
float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO;
float dx = (float) Math.cos(theta);
float dy = (float) Math.sin(theta);
float p0x = cx + dx * r0;
float p0y = cy + dy * r0;
float p1x = cx + dx * r1;
float p1y = cy + dy * r1;
float ox = (p1y - p0y);
float oy = -(p1x - p0x);
float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy);
ox *= norm;
oy *= norm;
path.moveTo(p0x - ox, p0y - oy);
path.lineTo(p1x - ox, p1y - oy);
path.lineTo(p1x + ox, p1y + oy);
path.lineTo(p0x + ox, p0y + oy);
path.close();
}
/**
* Adds a vertical arrow to the given Path.
*
* @param path the Path to draw to
*/
private static void drawVArrow(Path path,
float cx, float cy, float width, float height) {
path.moveTo(cx - width / 2.0f, cy);
path.lineTo(cx, cy + height);
path.lineTo(cx + width / 2.0f, cy);
path.close();
}
/**
* Adds a horizontal arrow to the given Path.
*
* @param path the Path to draw to
*/
private static void drawHArrow(Path path,
float cx, float cy, float width, float height) {
path.moveTo(cx, cy - height / 2.0f);
path.lineTo(cx + width, cy);
path.lineTo(cx, cy + height / 2.0f);
path.close();
}
/**
* Returns an offset in milliseconds to be subtracted from the current time
* in order to obtain an smooth interpolation between the previously
* displayed time and the current time.
*/
private long getOffset(float lerp) {
long doffset = (long) (mCity.getOffset() *
(float) MILLISECONDS_PER_HOUR - mOldOffset);
int sign;
if (doffset < 0) {
doffset = -doffset;
sign = -1;
} else {
sign = 1;
}
while (doffset > 12L * MILLISECONDS_PER_HOUR) {
doffset -= 12L * MILLISECONDS_PER_HOUR;
}
if (doffset > 6L * MILLISECONDS_PER_HOUR) {
doffset = 12L * MILLISECONDS_PER_HOUR - doffset;
sign = -sign;
}
// Interpolate doffset towards 0
doffset = (long)((1.0f - lerp)*doffset);
// Keep the same seconds count
long dh = doffset / (MILLISECONDS_PER_HOUR);
doffset -= dh * MILLISECONDS_PER_HOUR;
long dm = doffset / MILLISECONDS_PER_MINUTE;
doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE;
return doffset;
}
/**
* Set the city to be displayed. setCity(null) resets things so the clock
* hand animation won't occur next time.
*/
public void setCity(City city) {
if (mCity != city) {
if (mCity != null) {
mOldOffset =
(long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR);
} else if (city != null) {
mOldOffset =
(long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR);
} else {
mOldOffset = 0L; // this will never be used
}
this.mCitySwitchTime = System.currentTimeMillis();
this.mCity = city;
}
}
public void setTime(long time) {
this.mTime = time;
}
/**
* Draws the clock face.
*
* @param canvas the Canvas to draw to
* @param cx the X coordinate of the clock center
* @param cy the Y coordinate of the clock center
* @param radius the radius of the clock face
* @param alpha the translucency of the clock face
* @param textAlpha the translucency of the text
* @param showCityName if true, display the city name
* @param showTime if true, display the time digitally
* @param showUpArrow if true, display an up arrow
* @param showDownArrow if true, display a down arrow
* @param showLeftRightArrows if true, display left and right arrows
* @param prefixChars number of characters of the city name to draw in bold
*/
public void drawClock(Canvas canvas,
float cx, float cy, float radius, float alpha, float textAlpha,
boolean showCityName, boolean showTime,
boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows,
int prefixChars) {
Paint paint = new Paint();
paint.setAntiAlias(true);
int iradius = (int)radius;
TimeZone tz = mCity.getTimeZone();
// Compute an interpolated time to animate between the previously
// displayed time and the current time
float lerp = Math.min(1.0f,
(System.currentTimeMillis() - mCitySwitchTime) / 500.0f);
lerp = mClockHandInterpolator.getInterpolation(lerp);
long doffset = lerp < 1.0f ? getOffset(lerp) : 0L;
// Determine the interpolated time for the given time zone
Calendar cal = Calendar.getInstance(tz);
cal.setTimeInMillis(mTime - doffset);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int milli = cal.get(Calendar.MILLISECOND);
float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR;
float daylightOffset = tz.inDaylightTime(new Date(mTime)) ?
tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f;
float absOffset = offset < 0 ? -offset : offset;
int offsetH = (int) absOffset;
int offsetM = (int) (60.0f * (absOffset - offsetH));
hour %= 12;
// Get the city name and digital time strings
String cityName = mCity.getName();
cal.setTimeInMillis(mTime);
//java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext());
DateFormat mTimeFormat = DateFormat.getTimeInstance();
String time = mTimeFormat.format(cal.getTimeInMillis()) + " " +
DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK),
DateUtils.LENGTH_SHORT) + " " +
" (UTC" +
(offset >= 0 ? "+" : "-") +
offsetH +
(offsetM == 0 ? "" : ":" + offsetM) +
(daylightOffset == 0 ? "" : "+" + daylightOffset) +
")";
float th = paint.getTextSize();
float tw;
// Set the text color
paint.setARGB((int) (textAlpha * 255.0f),
(int) (mColorRed * 255.0f),
(int) (mColorGreen * 255.0f),
(int) (mColorBlue * 255.0f));
tw = paint.measureText(cityName);
if (showCityName) {
// Increment prefixChars to include any spaces
for (int i = 0; i < prefixChars; i++) {
if (cityName.charAt(i) == ' ') {
++prefixChars;
}
}
// Draw the city name
canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint);
// Overstrike the first 'prefixChars' characters
canvas.drawText(cityName.substring(0, prefixChars),
cx - tw / 2 + 1, cy - radius - th, paint);
}
tw = paint.measureText(time);
if (showTime) {
canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint);
}
paint.setARGB((int)(alpha * 255.0f),
(int)(mColorRed * 255.0f),
(int)(mColorGreen * 255.0f),
(int)(mColorBlue * 255.0f));
paint.setStyle(Paint.Style.FILL);
canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(radius * 0.12f);
canvas.drawOval(new RectF(cx - iradius, cy - iradius,
cx + iradius, cy + iradius),
paint);
float r0 = radius * 0.1f;
float r1 = radius * 0.4f;
float r2 = radius * 0.6f;
float r3 = radius * 0.65f;
float r4 = radius * 0.7f;
float r5 = radius * 0.9f;
Path path = new Path();
float ss = second + milli / 1000.0f;
float mm = minute + ss / 60.0f;
float hh = hour + mm / 60.0f;
// Tics for the hours
for (int i = 0; i < 12; i++) {
drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5);
}
// Hour hand
drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1);
// Minute hand
drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2);
// Second hand
drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3);
if (showUpArrow) {
drawVArrow(path, cx + radius * 1.13f, cy - radius,
radius * 0.15f, -radius * 0.1f);
}
if (showDownArrow) {
drawVArrow(path, cx + radius * 1.13f, cy + radius,
radius * 0.15f, radius * 0.1f);
}
if (showLeftRightArrows) {
drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f,
radius * 0.15f);
drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f,
radius * 0.15f);
}
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(path, paint);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
/**
* A class representing a set of GL_POINT objects. GlobalTime uses this class
* to draw city lights on the night side of the earth.
*/
public class PointCloud extends Shape {
/**
* Constructs a PointCloud with a point at each of the given vertex
* (x, y, z) positions.
* @param vertices an array of (x, y, z) positions given in fixed-point.
*/
public PointCloud(int[] vertices) {
this(vertices, 0, vertices.length);
}
/**
* Constructs a PointCloud with a point at each of the given vertex
* (x, y, z) positions.
* @param vertices an array of (x, y, z) positions given in fixed-point.
* @param off the starting offset of the vertices array
* @param len the number of elements of the vertices array to use
*/
public PointCloud(int[] vertices, int off, int len) {
super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT,
false, false, false);
int numPoints = len / 3;
short[] indices = new short[numPoints];
for (int i = 0; i < numPoints; i++) {
indices[i] = (short)i;
}
allocateBuffers(vertices, null, null, null, indices);
this.mNumIndices = mIndexBuffer.capacity();
}
@Override public int getNumTriangles() {
return mNumIndices * 2;
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
/**
* An abstract superclass for various three-dimensional objects to be drawn
* using OpenGL ES. Each subclass is responsible for setting up NIO buffers
* containing vertices, texture coordinates, colors, normals, and indices.
* The {@link #draw(GL10)} method draws the object to the given OpenGL context.
*/
public abstract class Shape {
public static final int INT_BYTES = 4;
public static final int SHORT_BYTES = 2;
public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f;
public static final float PI = (float) Math.PI;
public static final float TWO_PI = (float) (2.0 * Math.PI);
public static final float PI_OVER_TWO = (float) (Math.PI / 2.0);
protected int mPrimitive;
protected int mIndexDatatype;
protected boolean mEmitTextureCoordinates;
protected boolean mEmitNormals;
protected boolean mEmitColors;
protected IntBuffer mVertexBuffer;
protected IntBuffer mTexcoordBuffer;
protected IntBuffer mColorBuffer;
protected IntBuffer mNormalBuffer;
protected Buffer mIndexBuffer;
protected int mNumIndices = -1;
/**
* Constructs a Shape.
*
* @param primitive a GL primitive type understood by glDrawElements,
* such as GL10.GL_TRIANGLES
* @param indexDatatype the GL datatype for the index buffer, such as
* GL10.GL_UNSIGNED_SHORT
* @param emitTextureCoordinates true to enable use of the texture
* coordinate buffer
* @param emitNormals true to enable use of the normal buffer
* @param emitColors true to enable use of the color buffer
*/
protected Shape(int primitive,
int indexDatatype,
boolean emitTextureCoordinates,
boolean emitNormals,
boolean emitColors) {
mPrimitive = primitive;
mIndexDatatype = indexDatatype;
mEmitTextureCoordinates = emitTextureCoordinates;
mEmitNormals = emitNormals;
mEmitColors = emitColors;
}
/**
* Converts the given floating-point value to fixed-point.
*/
public static int toFixed(float x) {
return (int) (x * 65536.0);
}
/**
* Converts the given fixed-point value to floating-point.
*/
public static float toFloat(int x) {
return (float) (x / 65536.0);
}
/**
* Computes the cross-product of two vectors p and q and places
* the result in out.
*/
public static void cross(float[] p, float[] q, float[] out) {
out[0] = p[1] * q[2] - p[2] * q[1];
out[1] = p[2] * q[0] - p[0] * q[2];
out[2] = p[0] * q[1] - p[1] * q[0];
}
/**
* Returns the length of a vector, given as three floats.
*/
public static float length(float vx, float vy, float vz) {
return (float) Math.sqrt(vx * vx + vy * vy + vz * vz);
}
/**
* Returns the length of a vector, given as an array of three floats.
*/
public static float length(float[] v) {
return length(v[0], v[1], v[2]);
}
/**
* Normalizes the given vector of three floats to have length == 1.0.
* Vectors with length zero are unaffected.
*/
public static void normalize(float[] v) {
float length = length(v);
if (length != 0.0f) {
float norm = 1.0f / length;
v[0] *= norm;
v[1] *= norm;
v[2] *= norm;
}
}
/**
* Returns the number of triangles associated with this shape.
*/
public int getNumTriangles() {
if (mPrimitive == GL10.GL_TRIANGLES) {
return mIndexBuffer.capacity() / 3;
} else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) {
return mIndexBuffer.capacity() - 2;
}
return 0;
}
/**
* Copies the given data into the instance
* variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer,
* and mIndexBuffer.
*
* @param vertices an array of fixed-point vertex coordinates
* @param texcoords an array of fixed-point texture coordinates
* @param normals an array of fixed-point normal vector coordinates
* @param colors an array of fixed-point color channel values
* @param indices an array of short indices
*/
public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals,
int[] colors, short[] indices) {
allocate(vertices, texcoords, normals, colors);
ByteBuffer ibb =
ByteBuffer.allocateDirect(indices.length * SHORT_BYTES);
ibb.order(ByteOrder.nativeOrder());
ShortBuffer shortIndexBuffer = ibb.asShortBuffer();
shortIndexBuffer.put(indices);
shortIndexBuffer.position(0);
this.mIndexBuffer = shortIndexBuffer;
}
/**
* Copies the given data into the instance
* variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer,
* and mIndexBuffer.
*
* @param vertices an array of fixed-point vertex coordinates
* @param texcoords an array of fixed-point texture coordinates
* @param normals an array of fixed-point normal vector coordinates
* @param colors an array of fixed-point color channel values
* @param indices an array of int indices
*/
public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals,
int[] colors, int[] indices) {
allocate(vertices, texcoords, normals, colors);
ByteBuffer ibb =
ByteBuffer.allocateDirect(indices.length * INT_BYTES);
ibb.order(ByteOrder.nativeOrder());
IntBuffer intIndexBuffer = ibb.asIntBuffer();
intIndexBuffer.put(indices);
intIndexBuffer.position(0);
this.mIndexBuffer = intIndexBuffer;
}
/**
* Allocate the vertex, texture coordinate, normal, and color buffer.
*/
private void allocate(int[] vertices, int[] texcoords, int[] normals,
int[] colors) {
ByteBuffer vbb =
ByteBuffer.allocateDirect(vertices.length * INT_BYTES);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asIntBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
if ((texcoords != null) && mEmitTextureCoordinates) {
ByteBuffer tbb =
ByteBuffer.allocateDirect(texcoords.length * INT_BYTES);
tbb.order(ByteOrder.nativeOrder());
mTexcoordBuffer = tbb.asIntBuffer();
mTexcoordBuffer.put(texcoords);
mTexcoordBuffer.position(0);
}
if ((normals != null) && mEmitNormals) {
ByteBuffer nbb =
ByteBuffer.allocateDirect(normals.length * INT_BYTES);
nbb.order(ByteOrder.nativeOrder());
mNormalBuffer = nbb.asIntBuffer();
mNormalBuffer.put(normals);
mNormalBuffer.position(0);
}
if ((colors != null) && mEmitColors) {
ByteBuffer cbb =
ByteBuffer.allocateDirect(colors.length * INT_BYTES);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asIntBuffer();
mColorBuffer.put(colors);
mColorBuffer.position(0);
}
}
/**
* Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates,
* normals, and colors are emitted according the the preferences set for
* this shape.
*/
public void draw(GL10 gl) {
gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (mEmitTextureCoordinates) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (mEmitNormals) {
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer);
} else {
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
}
if (mEmitColors) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
gl.glDrawElements(mPrimitive,
mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(),
mIndexDatatype,
mIndexBuffer);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
/**
* A class that draws a ring with a given center and inner and outer radii.
* The inner and outer rings each have a color and the remaining pixels are
* colored by interpolation. GlobalTime uses this class to simulate an
* "atmosphere" around the earth.
*/
public class Annulus extends Shape {
/**
* Constructs an annulus.
*
* @param centerX the X coordinate of the center point
* @param centerY the Y coordinate of the center point
* @param Z the fixed Z for the entire ring
* @param innerRadius the inner radius
* @param outerRadius the outer radius
* @param rInner the red channel of the color of the inner ring
* @param gInner the green channel of the color of the inner ring
* @param bInner the blue channel of the color of the inner ring
* @param aInner the alpha channel of the color of the inner ring
* @param rOuter the red channel of the color of the outer ring
* @param gOuter the green channel of the color of the outer ring
* @param bOuter the blue channel of the color of the outer ring
* @param aOuter the alpha channel of the color of the outer ring
* @param sectors the number of sectors used to approximate curvature
*/
public Annulus(float centerX, float centerY, float Z,
float innerRadius, float outerRadius,
float rInner, float gInner, float bInner, float aInner,
float rOuter, float gOuter, float bOuter, float aOuter,
int sectors) {
super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT,
false, false, true);
int radii = sectors + 1;
int[] vertices = new int[2 * 3 * radii];
int[] colors = new int[2 * 4 * radii];
short[] indices = new short[2 * 3 * radii];
int vidx = 0;
int cidx = 0;
int iidx = 0;
for (int i = 0; i < radii; i++) {
float theta = (i * TWO_PI) / (radii - 1);
float cosTheta = (float) Math.cos(theta);
float sinTheta = (float) Math.sin(theta);
vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta);
vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta);
vertices[vidx++] = toFixed(Z);
vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta);
vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta);
vertices[vidx++] = toFixed(Z);
colors[cidx++] = toFixed(rInner);
colors[cidx++] = toFixed(gInner);
colors[cidx++] = toFixed(bInner);
colors[cidx++] = toFixed(aInner);
colors[cidx++] = toFixed(rOuter);
colors[cidx++] = toFixed(gOuter);
colors[cidx++] = toFixed(bOuter);
colors[cidx++] = toFixed(aOuter);
}
for (int i = 0; i < sectors; i++) {
indices[iidx++] = (short) (2 * i);
indices[iidx++] = (short) (2 * i + 1);
indices[iidx++] = (short) (2 * i + 2);
indices[iidx++] = (short) (2 * i + 1);
indices[iidx++] = (short) (2 * i + 3);
indices[iidx++] = (short) (2 * i + 2);
}
allocateBuffers(vertices, null, null, colors, indices);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import javax.microedition.khronos.egl.*;
import javax.microedition.khronos.opengles.*;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.opengl.Object3D;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
/**
* The main View of the GlobalTime Activity.
*/
class GTView extends SurfaceView implements SurfaceHolder.Callback {
/**
* A TimeZone object used to compute the current UTC time.
*/
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc");
/**
* The Sun's color is close to that of a 5780K blackbody.
*/
private static final float[] SUNLIGHT_COLOR = {
1.0f, 0.9375f, 0.91015625f, 1.0f
};
/**
* The inclination of the earth relative to the plane of the ecliptic
* is 23.45 degrees.
*/
private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f;
/** Seconds in a day */
private static final int SECONDS_PER_DAY = 24 * 60 * 60;
/** Flag for the depth test */
private static final boolean PERFORM_DEPTH_TEST= false;
/** Use raw time zone offsets, disregarding "summer time." If false,
* current offsets will be used, which requires a much longer startup time
* in order to sort the city database.
*/
private static final boolean USE_RAW_OFFSETS = true;
/**
* The earth's atmosphere.
*/
private static final Annulus ATMOSPHERE =
new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 50);
/**
* The tesselation of the earth by latitude.
*/
private static final int SPHERE_LATITUDES = 25;
/**
* The tesselation of the earth by longitude.
*/
private static int SPHERE_LONGITUDES = 25;
/**
* A flattened version of the earth. The normals are computed identically
* to those of the round earth, allowing the day/night lighting to be
* applied to the flattened surface.
*/
private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f,
SPHERE_LATITUDES, SPHERE_LONGITUDES,
0.0f, 360.0f, true, true, false, true);
/**
* The earth.
*/
private Object3D mWorld;
/**
* Geometry of the city lights
*/
private PointCloud mLights;
/**
* True if the activiy has been initialized.
*/
boolean mInitialized = false;
/**
* True if we're in alphabetic entry mode.
*/
private boolean mAlphaKeySet = false;
private EGLContext mEGLContext;
private EGLSurface mEGLSurface;
private EGLDisplay mEGLDisplay;
private EGLConfig mEGLConfig;
GLView mGLView;
// Rotation and tilt of the Earth
private float mRotAngle = 0.0f;
private float mTiltAngle = 0.0f;
// Rotational velocity of the orbiting viewer
private float mRotVelocity = 1.0f;
// Rotation of the flat view
private float mWrapX = 0.0f;
private float mWrapVelocity = 0.0f;
private float mWrapVelocityFactor = 0.01f;
// Toggle switches
private boolean mDisplayAtmosphere = true;
private boolean mDisplayClock = false;
private boolean mClockShowing = false;
private boolean mDisplayLights = false;
private boolean mDisplayWorld = true;
private boolean mDisplayWorldFlat = false;
private boolean mSmoothShading = true;
// City search string
private String mCityName = "";
// List of all cities
private List<City> mClockCities;
// List of cities matching a user-supplied prefix
private List<City> mCityNameMatches = new ArrayList<City>();
private List<City> mCities;
// Start time for clock fade animation
private long mClockFadeTime;
// Interpolator for clock fade animation
private Interpolator mClockSizeInterpolator =
new DecelerateInterpolator(1.0f);
// Index of current clock
private int mCityIndex;
// Current clock
private Clock mClock;
// City-to-city flight animation parameters
private boolean mFlyToCity = false;
private long mCityFlyStartTime;
private float mCityFlightTime;
private float mRotAngleStart, mRotAngleDest;
private float mTiltAngleStart, mTiltAngleDest;
// Interpolator for flight motion animation
private Interpolator mFlyToCityInterpolator =
new AccelerateDecelerateInterpolator();
private static int sNumLights;
private static int[] sLightCoords;
// static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>();
// Arrays for GL calls
private float[] mClipPlaneEquation = new float[4];
private float[] mLightDir = new float[4];
// Calendar for computing the Sun's position
Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE);
// Triangles drawn per frame
private int mNumTriangles;
private long startTime;
private static final int MOTION_NONE = 0;
private static final int MOTION_X = 1;
private static final int MOTION_Y = 2;
private static final int MIN_MANHATTAN_DISTANCE = 20;
private static final float ROTATION_FACTOR = 1.0f / 30.0f;
private static final float TILT_FACTOR = 0.35f;
// Touchscreen support
private float mMotionStartX;
private float mMotionStartY;
private float mMotionStartRotVelocity;
private float mMotionStartTiltAngle;
private int mMotionDirection;
public void surfaceCreated(SurfaceHolder holder) {
EGL10 egl = (EGL10)EGLContext.getEGL();
mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null);
egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// nothing to do
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// nothing to do
}
/**
* Set up the view.
*
* @param context the Context
* @param am an AssetManager to retrieve the city database from
*/
public GTView(Context context) {
super(context);
getHolder().addCallback(this);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU);
AssetManager am = context.getAssets();
startTime = System.currentTimeMillis();
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config);
mEGLConfig = configs[0];
mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null);
mEGLDisplay = dpy;
mClock = new Clock();
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
try {
loadAssets(am);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException(ioe);
} catch (ArrayIndexOutOfBoundsException aioobe) {
aioobe.printStackTrace();
throw new RuntimeException(aioobe);
}
}
/**
* Destroy the view.
*/
public void destroy() {
EGL10 egl = (EGL10)EGLContext.getEGL();
egl.eglMakeCurrent(mEGLDisplay,
egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT);
egl.eglDestroyContext(mEGLDisplay, mEGLContext);
egl.eglDestroySurface(mEGLDisplay, mEGLSurface);
egl.eglTerminate(mEGLDisplay);
mEGLContext = null;
}
/**
* Begin animation.
*/
public void startAnimating() {
mHandler.sendEmptyMessage(INVALIDATE);
}
/**
* Quit animation.
*/
public void stopAnimating() {
mHandler.removeMessages(INVALIDATE);
}
/**
* Read a two-byte integer from the input stream.
*/
private int readInt16(InputStream is) throws IOException {
int lo = is.read();
int hi = is.read();
return (hi << 8) | lo;
}
/**
* Returns the offset from UTC for the given city. If USE_RAW_OFFSETS
* is true, summer/daylight savings is ignored.
*/
private static float getOffset(City c) {
return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset();
}
private InputStream cache(InputStream is) throws IOException {
int nbytes = is.available();
byte[] data = new byte[nbytes];
int nread = 0;
while (nread < nbytes) {
nread += is.read(data, nread, nbytes - nread);
}
return new ByteArrayInputStream(data);
}
/**
* Load the city and lights databases.
*
* @param am the AssetManager to load from.
*/
private void loadAssets(final AssetManager am) throws IOException {
Locale locale = Locale.getDefault();
String language = locale.getLanguage();
String country = locale.getCountry();
InputStream cis = null;
try {
// Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat
cis = am.open("cities_" + language + "_" + country + ".dat");
} catch (FileNotFoundException e1) {
try {
// Look for (e.g.) cities_fr.dat or cities_fr.dat
cis = am.open("cities_" + language + ".dat");
} catch (FileNotFoundException e2) {
try {
// Use English city names by default
cis = am.open("cities_en.dat");
} catch (FileNotFoundException e3) {
throw e3;
}
}
}
cis = cache(cis);
City.loadCities(cis);
City[] cities;
if (USE_RAW_OFFSETS) {
cities = City.getCitiesByRawOffset();
} else {
cities = City.getCitiesByOffset();
}
mClockCities = new ArrayList<City>(cities.length);
for (int i = 0; i < cities.length; i++) {
mClockCities.add(cities[i]);
}
mCities = mClockCities;
mCityIndex = 0;
this.mWorld = new Object3D() {
@Override
public InputStream readFile(String filename)
throws IOException {
return cache(am.open(filename));
}
};
mWorld.load("world.gles");
// lights.dat has the following format. All integers
// are 16 bits, low byte first.
//
// width
// height
// N [# of lights]
// light 0 X [in the range 0 to (width - 1)]
// light 0 Y ]in the range 0 to (height - 1)]
// light 1 X [in the range 0 to (width - 1)]
// light 1 Y ]in the range 0 to (height - 1)]
// ...
// light (N - 1) X [in the range 0 to (width - 1)]
// light (N - 1) Y ]in the range 0 to (height - 1)]
//
// For a larger number of lights, it could make more
// sense to store the light positions in a bitmap
// and extract them manually
InputStream lis = am.open("lights.dat");
lis = cache(lis);
int lightWidth = readInt16(lis);
int lightHeight = readInt16(lis);
sNumLights = readInt16(lis);
sLightCoords = new int[3 * sNumLights];
int lidx = 0;
float lightRadius = 1.009f;
float lightScale = 65536.0f * lightRadius;
float[] cosTheta = new float[lightWidth];
float[] sinTheta = new float[lightWidth];
float twoPi = (float) (2.0 * Math.PI);
float scaleW = twoPi / lightWidth;
for (int i = 0; i < lightWidth; i++) {
float theta = twoPi - i * scaleW;
cosTheta[i] = (float)Math.cos(theta);
sinTheta[i] = (float)Math.sin(theta);
}
float[] cosPhi = new float[lightHeight];
float[] sinPhi = new float[lightHeight];
float scaleH = (float) (Math.PI / lightHeight);
for (int j = 0; j < lightHeight; j++) {
float phi = j * scaleH;
cosPhi[j] = (float)Math.cos(phi);
sinPhi[j] = (float)Math.sin(phi);
}
int nbytes = 4 * sNumLights;
byte[] ilights = new byte[nbytes];
int nread = 0;
while (nread < nbytes) {
nread += lis.read(ilights, nread, nbytes - nread);
}
int idx = 0;
for (int i = 0; i < sNumLights; i++) {
int lx = (((ilights[idx + 1] & 0xff) << 8) |
(ilights[idx ] & 0xff));
int ly = (((ilights[idx + 3] & 0xff) << 8) |
(ilights[idx + 2] & 0xff));
idx += 4;
float sin = sinPhi[ly];
float x = cosTheta[lx]*sin;
float y = cosPhi[ly];
float z = sinTheta[lx]*sin;
sLightCoords[lidx++] = (int) (x * lightScale);
sLightCoords[lidx++] = (int) (y * lightScale);
sLightCoords[lidx++] = (int) (z * lightScale);
}
mLights = new PointCloud(sLightCoords);
}
/**
* Returns true if two time zone offsets are equal. We assume distinct
* time zone offsets will differ by at least a few minutes.
*/
private boolean tzEqual(float o1, float o2) {
return Math.abs(o1 - o2) < 0.001;
}
/**
* Move to a different time zone.
*
* @param incr The increment between the current and future time zones.
*/
private void shiftTimeZone(int incr) {
// If only 1 city in the current set, there's nowhere to go
if (mCities.size() <= 1) {
return;
}
float offset = getOffset(mCities.get(mCityIndex));
do {
mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size();
} while (tzEqual(getOffset(mCities.get(mCityIndex)), offset));
offset = getOffset(mCities.get(mCityIndex));
locateCity(true, offset);
goToCity();
}
/**
* Returns true if there is another city within the current time zone
* that is the given increment away from the current city.
*
* @param incr the increment, +1 or -1
* @return
*/
private boolean atEndOfTimeZone(int incr) {
if (mCities.size() <= 1) {
return true;
}
float offset = getOffset(mCities.get(mCityIndex));
int nindex = (mCityIndex + mCities.size() + incr) % mCities.size();
if (tzEqual(getOffset(mCities.get(nindex)), offset)) {
return false;
}
return true;
}
/**
* Shifts cities within the current time zone.
*
* @param incr the increment, +1 or -1
*/
private void shiftWithinTimeZone(int incr) {
float offset = getOffset(mCities.get(mCityIndex));
int nindex = (mCityIndex + mCities.size() + incr) % mCities.size();
if (tzEqual(getOffset(mCities.get(nindex)), offset)) {
mCityIndex = nindex;
goToCity();
}
}
/**
* Returns true if the city name matches the given prefix, ignoring spaces.
*/
private boolean nameMatches(City city, String prefix) {
String cityName = city.getName().replaceAll("[ ]", "");
return prefix.regionMatches(true, 0,
cityName, 0,
prefix.length());
}
/**
* Returns true if there are cities matching the given name prefix.
*/
private boolean hasMatches(String prefix) {
for (int i = 0; i < mClockCities.size(); i++) {
City city = mClockCities.get(i);
if (nameMatches(city, prefix)) {
return true;
}
}
return false;
}
/**
* Shifts to the nearest city that matches the new prefix.
*/
private void shiftByName() {
// Attempt to keep current city if it matches
City finalCity = null;
City currCity = mCities.get(mCityIndex);
if (nameMatches(currCity, mCityName)) {
finalCity = currCity;
}
mCityNameMatches.clear();
for (int i = 0; i < mClockCities.size(); i++) {
City city = mClockCities.get(i);
if (nameMatches(city, mCityName)) {
mCityNameMatches.add(city);
}
}
mCities = mCityNameMatches;
if (finalCity != null) {
for (int i = 0; i < mCityNameMatches.size(); i++) {
if (mCityNameMatches.get(i) == finalCity) {
mCityIndex = i;
break;
}
}
} else {
// Find the closest matching city
locateCity(false, 0.0f);
}
goToCity();
}
/**
* Increases or decreases the rotational speed of the earth.
*/
private void incrementRotationalVelocity(float incr) {
if (mDisplayWorldFlat) {
mWrapVelocity -= incr;
} else {
mRotVelocity -= incr;
}
}
/**
* Clears the current matching prefix, while keeping the focus on
* the current city.
*/
private void clearCityMatches() {
// Determine the global city index that matches the current city
if (mCityNameMatches.size() > 0) {
City city = mCityNameMatches.get(mCityIndex);
for (int i = 0; i < mClockCities.size(); i++) {
City ncity = mClockCities.get(i);
if (city.equals(ncity)) {
mCityIndex = i;
break;
}
}
}
mCityName = "";
mCityNameMatches.clear();
mCities = mClockCities;
goToCity();
}
/**
* Fade the clock in or out.
*/
private void enableClock(boolean enabled) {
mClockFadeTime = System.currentTimeMillis();
mDisplayClock = enabled;
mClockShowing = true;
mAlphaKeySet = enabled;
if (enabled) {
// Find the closest matching city
locateCity(false, 0.0f);
}
clearCityMatches();
}
/**
* Use the touchscreen to alter the rotational velocity or the
* tilt of the earth.
*/
@Override public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mMotionStartX = event.getX();
mMotionStartY = event.getY();
mMotionStartRotVelocity = mDisplayWorldFlat ?
mWrapVelocity : mRotVelocity;
mMotionStartTiltAngle = mTiltAngle;
// Stop the rotation
if (mDisplayWorldFlat) {
mWrapVelocity = 0.0f;
} else {
mRotVelocity = 0.0f;
}
mMotionDirection = MOTION_NONE;
break;
case MotionEvent.ACTION_MOVE:
// Disregard motion events when the clock is displayed
float dx = event.getX() - mMotionStartX;
float dy = event.getY() - mMotionStartY;
float delx = Math.abs(dx);
float dely = Math.abs(dy);
// Determine the direction of motion (major axis)
// Once if has been determined, it's locked in until
// we receive ACTION_UP or ACTION_CANCEL
if ((mMotionDirection == MOTION_NONE) &&
(delx + dely > MIN_MANHATTAN_DISTANCE)) {
if (delx > dely) {
mMotionDirection = MOTION_X;
} else {
mMotionDirection = MOTION_Y;
}
}
// If the clock is displayed, don't actually rotate or tilt;
// just use mMotionDirection to record whether motion occurred
if (!mDisplayClock) {
if (mMotionDirection == MOTION_X) {
if (mDisplayWorldFlat) {
mWrapVelocity = mMotionStartRotVelocity +
dx * ROTATION_FACTOR;
} else {
mRotVelocity = mMotionStartRotVelocity +
dx * ROTATION_FACTOR;
}
mClock.setCity(null);
} else if (mMotionDirection == MOTION_Y &&
!mDisplayWorldFlat) {
mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR;
if (mTiltAngle < -90.0f) {
mTiltAngle = -90.0f;
}
if (mTiltAngle > 90.0f) {
mTiltAngle = 90.0f;
}
mClock.setCity(null);
}
}
break;
case MotionEvent.ACTION_UP:
mMotionDirection = MOTION_NONE;
break;
case MotionEvent.ACTION_CANCEL:
mTiltAngle = mMotionStartTiltAngle;
if (mDisplayWorldFlat) {
mWrapVelocity = mMotionStartRotVelocity;
} else {
mRotVelocity = mMotionStartRotVelocity;
}
mMotionDirection = MOTION_NONE;
break;
}
return true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mInitialized && mGLView.processKey(keyCode)) {
boolean drawing = (mClockShowing || mGLView.hasMessages());
this.setWillNotDraw(!drawing);
return true;
}
boolean handled = false;
// If we're not in alphabetical entry mode, convert letters
// to their digit equivalents
if (!mAlphaKeySet) {
char numChar = event.getNumber();
if (numChar >= '0' && numChar <= '9') {
keyCode = KeyEvent.KEYCODE_0 + (numChar - '0');
}
}
switch (keyCode) {
// The 'space' key toggles the clock
case KeyEvent.KEYCODE_SPACE:
mAlphaKeySet = !mAlphaKeySet;
enableClock(mAlphaKeySet);
handled = true;
break;
// The 'left' and 'right' buttons shift time zones if the clock is
// displayed, otherwise they alters the rotational speed of the earthh
case KeyEvent.KEYCODE_DPAD_LEFT:
if (mDisplayClock) {
shiftTimeZone(-1);
} else {
mClock.setCity(null);
incrementRotationalVelocity(1.0f);
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (mDisplayClock) {
shiftTimeZone(1);
} else {
mClock.setCity(null);
incrementRotationalVelocity(-1.0f);
}
handled = true;
break;
// The 'up' and 'down' buttons shift cities within a time zone if the
// clock is displayed, otherwise they tilt the earth
case KeyEvent.KEYCODE_DPAD_UP:
if (mDisplayClock) {
shiftWithinTimeZone(-1);
} else {
mClock.setCity(null);
if (!mDisplayWorldFlat) {
mTiltAngle += 360.0f / 48.0f;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mDisplayClock) {
shiftWithinTimeZone(1);
} else {
mClock.setCity(null);
if (!mDisplayWorldFlat) {
mTiltAngle -= 360.0f / 48.0f;
}
}
handled = true;
break;
// The center key stops the earth's rotation, then toggles between the
// round and flat views of the earth
case KeyEvent.KEYCODE_DPAD_CENTER:
if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) ||
(mDisplayWorldFlat && mWrapVelocity == 0.0f)) {
mDisplayWorldFlat = !mDisplayWorldFlat;
} else {
if (mDisplayWorldFlat) {
mWrapVelocity = 0.0f;
} else {
mRotVelocity = 0.0f;
}
}
handled = true;
break;
// The 'L' key toggles the city lights
case KeyEvent.KEYCODE_L:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayLights = !mDisplayLights;
handled = true;
}
break;
// The 'W' key toggles the earth (just for fun)
case KeyEvent.KEYCODE_W:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayWorld = !mDisplayWorld;
handled = true;
}
break;
// The 'A' key toggles the atmosphere
case KeyEvent.KEYCODE_A:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayAtmosphere = !mDisplayAtmosphere;
handled = true;
}
break;
// The '2' key zooms out
case KeyEvent.KEYCODE_2:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mGLView.zoom(-2);
handled = true;
}
break;
// The '8' key zooms in
case KeyEvent.KEYCODE_8:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mGLView.zoom(2);
handled = true;
}
break;
}
// Handle letters in city names
if (!handled && mAlphaKeySet) {
switch (keyCode) {
// Add a letter to the city name prefix
case KeyEvent.KEYCODE_A:
case KeyEvent.KEYCODE_B:
case KeyEvent.KEYCODE_C:
case KeyEvent.KEYCODE_D:
case KeyEvent.KEYCODE_E:
case KeyEvent.KEYCODE_F:
case KeyEvent.KEYCODE_G:
case KeyEvent.KEYCODE_H:
case KeyEvent.KEYCODE_I:
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_K:
case KeyEvent.KEYCODE_L:
case KeyEvent.KEYCODE_M:
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_O:
case KeyEvent.KEYCODE_P:
case KeyEvent.KEYCODE_Q:
case KeyEvent.KEYCODE_R:
case KeyEvent.KEYCODE_S:
case KeyEvent.KEYCODE_T:
case KeyEvent.KEYCODE_U:
case KeyEvent.KEYCODE_V:
case KeyEvent.KEYCODE_W:
case KeyEvent.KEYCODE_X:
case KeyEvent.KEYCODE_Y:
case KeyEvent.KEYCODE_Z:
char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A');
if (hasMatches(mCityName + c)) {
mCityName += c;
shiftByName();
}
handled = true;
break;
// Remove a letter from the city name prefix
case KeyEvent.KEYCODE_DEL:
if (mCityName.length() > 0) {
mCityName = mCityName.substring(0, mCityName.length() - 1);
shiftByName();
} else {
clearCityMatches();
}
handled = true;
break;
// Clear the city name prefix
case KeyEvent.KEYCODE_ENTER:
clearCityMatches();
handled = true;
break;
}
}
boolean drawing = (mClockShowing ||
((mGLView != null) && (mGLView.hasMessages())));
this.setWillNotDraw(!drawing);
// Let the system handle other keypresses
if (!handled) {
return super.onKeyDown(keyCode, event);
}
return true;
}
/**
* Initialize OpenGL ES drawing.
*/
private synchronized void init(GL10 gl) {
mGLView = new GLView();
mGLView.setNearFrustum(5.0f);
mGLView.setFarFrustum(50.0f);
mGLView.setLightModelAmbientIntensity(0.225f);
mGLView.setAmbientIntensity(0.0f);
mGLView.setDiffuseIntensity(1.5f);
mGLView.setDiffuseColor(SUNLIGHT_COLOR);
mGLView.setSpecularIntensity(0.0f);
mGLView.setSpecularColor(SUNLIGHT_COLOR);
if (PERFORM_DEPTH_TEST) {
gl.glEnable(GL10.GL_DEPTH_TEST);
}
gl.glDisable(GL10.GL_SCISSOR_TEST);
gl.glClearColor(0, 0, 0, 1);
gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST);
mInitialized = true;
}
/**
* Computes the vector from the center of the earth to the sun for a
* particular moment in time.
*/
private void computeSunDirection() {
mSunCal.setTimeInMillis(System.currentTimeMillis());
int day = mSunCal.get(Calendar.DAY_OF_YEAR);
int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) +
60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND);
day += (float) seconds / SECONDS_PER_DAY;
// Approximate declination of the sun, changes sinusoidally
// during the year. The winter solstice occurs 10 days before
// the start of the year.
float decl = (float) (EARTH_INCLINATION *
Math.cos(Shape.TWO_PI * (day + 10) / 365.0));
// Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form
float phi = decl + Shape.PI_OVER_TWO;
// Subsolar longitude
float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY;
float sinPhi = (float) Math.sin(phi);
float cosPhi = (float) Math.cos(phi);
float sinTheta = (float) Math.sin(theta);
float cosTheta = (float) Math.cos(theta);
// Convert from polar to rectangular coordinates
float x = cosTheta * sinPhi;
float y = cosPhi;
float z = sinTheta * sinPhi;
// Directional light -> w == 0
mLightDir[0] = x;
mLightDir[1] = y;
mLightDir[2] = z;
mLightDir[3] = 0.0f;
}
/**
* Computes the approximate spherical distance between two
* (latitude, longitude) coordinates.
*/
private float distance(float lat1, float lon1,
float lat2, float lon2) {
lat1 *= Shape.DEGREES_TO_RADIANS;
lat2 *= Shape.DEGREES_TO_RADIANS;
lon1 *= Shape.DEGREES_TO_RADIANS;
lon2 *= Shape.DEGREES_TO_RADIANS;
float r = 6371.0f; // Earth's radius in km
float dlat = lat2 - lat1;
float dlon = lon2 - lon1;
double sinlat2 = Math.sin(dlat / 2.0f);
sinlat2 *= sinlat2;
double sinlon2 = Math.sin(dlon / 2.0f);
sinlon2 *= sinlon2;
double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2;
double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (float) (r * c);
}
/**
* Locates the closest city to the currently displayed center point,
* optionally restricting the search to cities within a given time zone.
*/
private void locateCity(boolean useOffset, float offset) {
float mindist = Float.MAX_VALUE;
int minidx = -1;
for (int i = 0; i < mCities.size(); i++) {
City city = mCities.get(i);
if (useOffset && !tzEqual(getOffset(city), offset)) {
continue;
}
float dist = distance(city.getLatitude(), city.getLongitude(),
mTiltAngle, mRotAngle - 90.0f);
if (dist < mindist) {
mindist = dist;
minidx = i;
}
}
mCityIndex = minidx;
}
/**
* Animates the earth to be centered at the current city.
*/
private void goToCity() {
City city = mCities.get(mCityIndex);
float dist = distance(city.getLatitude(), city.getLongitude(),
mTiltAngle, mRotAngle - 90.0f);
mFlyToCity = true;
mCityFlyStartTime = System.currentTimeMillis();
mCityFlightTime = dist / 5.0f; // 5000 km/sec
mRotAngleStart = mRotAngle;
mRotAngleDest = city.getLongitude() + 90;
if (mRotAngleDest - mRotAngleStart > 180.0f) {
mRotAngleDest -= 360.0f;
} else if (mRotAngleStart - mRotAngleDest > 180.0f) {
mRotAngleDest += 360.0f;
}
mTiltAngleStart = mTiltAngle;
mTiltAngleDest = city.getLatitude();
mRotVelocity = 0.0f;
}
/**
* Returns a linearly interpolated value between two values.
*/
private float lerp(float a, float b, float lerp) {
return a + (b - a)*lerp;
}
/**
* Draws the city lights, using a clip plane to restrict the lights
* to the night side of the earth.
*/
private void drawCityLights(GL10 gl, float brightness) {
gl.glEnable(GL10.GL_POINT_SMOOTH);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_DITHER);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glPointSize(1.0f);
float ls = lerp(0.8f, 0.3f, brightness);
gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f);
if (mDisplayWorld) {
mClipPlaneEquation[0] = -mLightDir[0];
mClipPlaneEquation[1] = -mLightDir[1];
mClipPlaneEquation[2] = -mLightDir[2];
mClipPlaneEquation[3] = 0.0f;
// Assume we have glClipPlanef() from OpenGL ES 1.1
((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0,
mClipPlaneEquation, 0);
gl.glEnable(GL11.GL_CLIP_PLANE0);
}
mLights.draw(gl);
if (mDisplayWorld) {
gl.glDisable(GL11.GL_CLIP_PLANE0);
}
mNumTriangles += mLights.getNumTriangles()*2;
}
/**
* Draws the atmosphere.
*/
private void drawAtmosphere(GL10 gl) {
gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
// Draw the atmospheric layer
float tx = mGLView.getTranslateX();
float ty = mGLView.getTranslateY();
float tz = mGLView.getTranslateZ();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(tx, ty, tz);
// Blend in the atmosphere a bit
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
ATMOSPHERE.draw(gl);
mNumTriangles += ATMOSPHERE.getNumTriangles();
}
/**
* Draws the world in a 2D map view.
*/
private void drawWorldFlat(GL10 gl) {
gl.glDisable(GL10.GL_BLEND);
gl.glEnable(GL10.GL_DITHER);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f);
worldFlat.draw(gl);
gl.glTranslatef(2.0f, 0.0f, 0.0f);
worldFlat.draw(gl);
mNumTriangles += worldFlat.getNumTriangles() * 2;
mWrapX += mWrapVelocity * mWrapVelocityFactor;
while (mWrapX < 0.0f) {
mWrapX += 2.0f;
}
while (mWrapX > 2.0f) {
mWrapX -= 2.0f;
}
}
/**
* Draws the world in a 2D round view.
*/
private void drawWorldRound(GL10 gl) {
gl.glDisable(GL10.GL_BLEND);
gl.glEnable(GL10.GL_DITHER);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
mWorld.draw(gl);
mNumTriangles += mWorld.getNumTriangles();
}
/**
* Draws the clock.
*
* @param canvas the Canvas to draw to
* @param now the current time
* @param w the width of the screen
* @param h the height of the screen
* @param lerp controls the animation, between 0.0 and 1.0
*/
private void drawClock(Canvas canvas,
long now,
int w, int h,
float lerp) {
float clockAlpha = lerp(0.0f, 0.8f, lerp);
mClockShowing = clockAlpha > 0.0f;
if (clockAlpha > 0.0f) {
City city = mCities.get(mCityIndex);
mClock.setCity(city);
mClock.setTime(now);
float cx = w / 2.0f;
float cy = h / 2.0f;
float smallRadius = 18.0f;
float bigRadius = 0.75f * 0.5f * Math.min(w, h);
float radius = lerp(smallRadius, bigRadius, lerp);
// Only display left/right arrows if we are in a name search
boolean scrollingByName =
(mCityName.length() > 0) && (mCities.size() > 1);
mClock.drawClock(canvas, cx, cy, radius,
clockAlpha,
1.0f,
lerp == 1.0f, lerp == 1.0f,
!atEndOfTimeZone(-1),
!atEndOfTimeZone(1),
scrollingByName,
mCityName.length());
}
}
/**
* Draws the 2D layer.
*/
@Override protected void onDraw(Canvas canvas) {
long now = System.currentTimeMillis();
if (startTime != -1) {
startTime = -1;
}
int w = getWidth();
int h = getHeight();
// Interpolator for clock size, clock alpha, night lights intensity
float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f);
if (!mDisplayClock) {
// Clock is receding
lerp = 1.0f - lerp;
}
lerp = mClockSizeInterpolator.getInterpolation(lerp);
// we don't need to make sure OpenGL rendering is done because
// we're drawing in to a different surface
drawClock(canvas, now, w, h, lerp);
mGLView.showMessages(canvas);
mGLView.showStatistics(canvas, w);
}
/**
* Draws the 3D layer.
*/
protected void drawOpenGLScene() {
long now = System.currentTimeMillis();
mNumTriangles = 0;
EGL10 egl = (EGL10)EGLContext.getEGL();
GL10 gl = (GL10)mEGLContext.getGL();
if (!mInitialized) {
init(gl);
}
int w = getWidth();
int h = getHeight();
gl.glViewport(0, 0, w, h);
gl.glEnable(GL10.GL_LIGHTING);
gl.glEnable(GL10.GL_LIGHT0);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glFrontFace(GL10.GL_CCW);
float ratio = (float) w / h;
mGLView.setAspectRatio(ratio);
mGLView.setTextureParameters(gl);
if (PERFORM_DEPTH_TEST) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
} else {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
if (mDisplayWorldFlat) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -1.0f);
} else {
mGLView.setProjection(gl);
mGLView.setView(gl);
}
if (!mDisplayWorldFlat) {
if (mFlyToCity) {
float lerp = (now - mCityFlyStartTime)/mCityFlightTime;
if (lerp >= 1.0f) {
mFlyToCity = false;
}
lerp = Math.min(lerp, 1.0f);
lerp = mFlyToCityInterpolator.getInterpolation(lerp);
mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp);
mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp);
}
// Rotate the viewpoint around the earth
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glRotatef(mTiltAngle, 1, 0, 0);
gl.glRotatef(mRotAngle, 0, 1, 0);
// Increment the rotation angle
mRotAngle += mRotVelocity;
if (mRotAngle < 0.0f) {
mRotAngle += 360.0f;
}
if (mRotAngle > 360.0f) {
mRotAngle -= 360.0f;
}
}
// Draw the world with lighting
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0);
mGLView.setLights(gl, GL10.GL_LIGHT0);
if (mDisplayWorldFlat) {
drawWorldFlat(gl);
} else if (mDisplayWorld) {
drawWorldRound(gl);
}
if (mDisplayLights && !mDisplayWorldFlat) {
// Interpolator for clock size, clock alpha, night lights intensity
float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f);
if (!mDisplayClock) {
// Clock is receding
lerp = 1.0f - lerp;
}
lerp = mClockSizeInterpolator.getInterpolation(lerp);
drawCityLights(gl, lerp);
}
if (mDisplayAtmosphere && !mDisplayWorldFlat) {
drawAtmosphere(gl);
}
mGLView.setNumTriangles(mNumTriangles);
egl.eglSwapBuffers(mEGLDisplay, mEGLSurface);
if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) {
// we lost the gpu, quit immediately
Context c = getContext();
if (c instanceof Activity) {
((Activity)c).finish();
}
}
}
private static final int INVALIDATE = 1;
private static final int ONE_MINUTE = 60000;
/**
* Controls the animation using the message queue. Every time we receive
* an INVALIDATE message, we redraw and place another message in the queue.
*/
private final Handler mHandler = new Handler() {
private long mLastSunPositionTime = 0;
@Override public void handleMessage(Message msg) {
if (msg.what == INVALIDATE) {
// Use the message's time, it's good enough and
// allows us to avoid a system call.
if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) {
// Recompute the sun's position once per minute
// Place the light at the Sun's direction
computeSunDirection();
mLastSunPositionTime = msg.getWhen();
}
// Draw the GL scene
drawOpenGLScene();
// Send an update for the 2D overlay if needed
if (mInitialized &&
(mClockShowing || mGLView.hasMessages())) {
invalidate();
}
// Just send another message immediately. This works because
// drawOpenGLScene() does the timing for us -- it will
// block until the last frame has been processed.
// The invalidate message we're posting here will be
// interleaved properly with motion/key events which
// guarantee a prompt reaction to the user input.
sendEmptyMessage(INVALIDATE);
}
}
};
}
/**
* The main activity class for GlobalTime.
*/
public class GlobalTime extends Activity {
GTView gtView = null;
private void setGTView() {
if (gtView == null) {
gtView = new GTView(this);
setContentView(gtView);
}
}
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setGTView();
}
@Override protected void onResume() {
super.onResume();
setGTView();
Looper.myQueue().addIdleHandler(new Idler());
}
@Override protected void onPause() {
super.onPause();
gtView.stopAnimating();
}
@Override protected void onStop() {
super.onStop();
gtView.stopAnimating();
gtView.destroy();
gtView = null;
}
// Allow the activity to go idle before its animation starts
class Idler implements MessageQueue.IdleHandler {
public Idler() {
super();
}
public final boolean queueIdle() {
if (gtView != null) {
gtView.startAnimating();
}
return false;
}
}
}
| Java |
/*
* Copyright (C) 2006-2007 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.android.globaltime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
class Message {
private String mText;
private long mExpirationTime;
public Message(String text, long expirationTime) {
this.mText = text;
this.mExpirationTime = expirationTime;
}
public String getText() {
return mText;
}
public long getExpirationTime() {
return mExpirationTime;
}
}
/**
* A helper class to simplify writing an Activity that renders using
* OpenGL ES.
*
* <p> A GLView object stores common elements of GL state and allows
* them to be modified interactively. This is particularly useful for
* determining the proper settings of parameters such as the view
* frustum and light intensities during application development.
*
* <p> A GLView is not an actual View; instead, it is meant to be
* called from within a View to perform event processing on behalf of the
* actual View.
*
* <p> By passing key events to the GLView object from the View,
* the application can automatically allow certain parameters to
* be user-controlled from the keyboard. Key events may be passed as
* shown below:
*
* <pre>
* GLView mGlView = new GLView();
*
* public boolean onKeyDown(int keyCode, KeyEvent event) {
* // Hand the key to the GLView object first
* if (mGlView.processKey(keyCode)) {
* return;
* }
*
* switch (keyCode) {
* case KeyEvent.KEY_CODE_X:
* // perform app processing
* break;
*
* default:
* super.onKeyDown(keyCode, event);
* break;
* }
* }
* </pre>
*
* <p> During drawing of a frame, the GLView object should be given the
* opportunity to manage GL parameters as shown below:
*
* OpenGLContext mGLContext; // initialization not shown
* int mNumTrianglesDrawn = 0;
*
* protected void onDraw(Canvas canvas) {
* int w = getWidth();
* int h = getHeight();
*
* float ratio = (float) w / h;
* mGLView.setAspectRatio(ratio);
*
* GL10 gl = (GL10) mGLContext.getGL();
* mGLContext.waitNative(canvas, this);
*
* // Enable a light for the GLView to manipulate
* gl.glEnable(GL10.GL_LIGHTING);
* gl.glEnable(GL10.GL_LIGHT0);
*
* // Allow the GLView to set GL parameters
* mGLView.setTextureParameters(gl);
* mGLView.setProjection(gl);
* mGLView.setView(gl);
* mGLView.setLights(gl, GL10.GL_LIGHT0);
*
* // Draw some stuff (not shown)
* mNumTrianglesDrawn += <num triangles just drawn>;
*
* // Wait for GL drawing to complete
* mGLContext.waitGL();
*
* // Inform the GLView of what was drawn, and ask it to display statistics
* mGLView.setNumTriangles(mNumTrianglesDrawn);
* mGLView.showMessages(canvas);
* mGLView.showStatistics(canvas, w);
* }
* </pre>
*
* <p> At the end of each frame, following the call to
* GLContext.waitGL, the showStatistics and showMessages methods
* will cause additional information to be displayed.
*
* <p> To enter the interactive command mode, the 'tab' key must be
* pressed twice in succession. A subsequent press of the 'tab' key
* exits the interactive command mode. Entering a multi-letter code
* sets the parameter to be modified. The 'newline' key erases the
* current code, and the 'del' key deletes the last letter of
* the code. The parameter value may be modified by pressing the
* keypad left or up to decrement the value and right or down to
* increment the value. The current value will be displayed as an
* overlay above the GL rendered content.
*
* <p> The supported keyboard commands are as follows:
*
* <ul>
* <li> h - display a list of commands
* <li> fn - near frustum
* <li> ff - far frustum
* <li> tx - translate x
* <li> ty - translate y
* <li> tz - translate z
* <li> z - zoom (frustum size)
* <li> la - ambient light (all RGB channels)
* <li> lar - ambient light red channel
* <li> lag - ambient light green channel
* <li> lab - ambient light blue channel
* <li> ld - diffuse light (all RGB channels)
* <li> ldr - diffuse light red channel
* <li> ldg - diffuse light green channel
* <li> ldb - diffuse light blue channel
* <li> ls - specular light (all RGB channels)
* <li> lsr - specular light red channel
* <li> lsg - specular light green channel
* <li> lsb - specular light blue channel
* <li> lma - light model ambient (all RGB channels)
* <li> lmar - light model ambient light red channel
* <li> lmag - light model ambient green channel
* <li> lmab - light model ambient blue channel
* <li> tmin - texture min filter
* <li> tmag - texture mag filter
* <li> tper - texture perspective correction
* </ul>
*
* {@hide}
*/
public class GLView {
private static final int DEFAULT_DURATION_MILLIS = 1000;
private static final int STATE_KEY = KeyEvent.KEYCODE_TAB;
private static final int HAVE_NONE = 0;
private static final int HAVE_ONE = 1;
private static final int HAVE_TWO = 2;
private static final float MESSAGE_Y_SPACING = 12.0f;
private int mState = HAVE_NONE;
private static final int NEAR_FRUSTUM = 0;
private static final int FAR_FRUSTUM = 1;
private static final int TRANSLATE_X = 2;
private static final int TRANSLATE_Y = 3;
private static final int TRANSLATE_Z = 4;
private static final int ZOOM_EXPONENT = 5;
private static final int AMBIENT_INTENSITY = 6;
private static final int AMBIENT_RED = 7;
private static final int AMBIENT_GREEN = 8;
private static final int AMBIENT_BLUE = 9;
private static final int DIFFUSE_INTENSITY = 10;
private static final int DIFFUSE_RED = 11;
private static final int DIFFUSE_GREEN = 12;
private static final int DIFFUSE_BLUE = 13;
private static final int SPECULAR_INTENSITY = 14;
private static final int SPECULAR_RED = 15;
private static final int SPECULAR_GREEN = 16;
private static final int SPECULAR_BLUE = 17;
private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18;
private static final int LIGHT_MODEL_AMBIENT_RED = 19;
private static final int LIGHT_MODEL_AMBIENT_GREEN = 20;
private static final int LIGHT_MODEL_AMBIENT_BLUE = 21;
private static final int TEXTURE_MIN_FILTER = 22;
private static final int TEXTURE_MAG_FILTER = 23;
private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24;
private static final String[] commands = {
"fn",
"ff",
"tx",
"ty",
"tz",
"z",
"la", "lar", "lag", "lab",
"ld", "ldr", "ldg", "ldb",
"ls", "lsr", "lsg", "lsb",
"lma", "lmar", "lmag", "lmab",
"tmin", "tmag", "tper"
};
private static final String[] labels = {
"Near Frustum",
"Far Frustum",
"Translate X",
"Translate Y",
"Translate Z",
"Zoom",
"Ambient Intensity",
"Ambient Red",
"Ambient Green",
"Ambient Blue",
"Diffuse Intensity",
"Diffuse Red",
"Diffuse Green",
"Diffuse Blue",
"Specular Intenstity",
"Specular Red",
"Specular Green",
"Specular Blue",
"Light Model Ambient Intensity",
"Light Model Ambient Red",
"Light Model Ambient Green",
"Light Model Ambient Blue",
"Texture Min Filter",
"Texture Mag Filter",
"Texture Perspective Correction",
};
private static final float[] defaults = {
5.0f, 100.0f,
0.0f, 0.0f, -50.0f,
0,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
GL10.GL_NEAREST, GL10.GL_NEAREST,
GL10.GL_FASTEST
};
private static final float[] increments = {
0.01f, 0.5f,
0.125f, 0.125f, 0.125f,
1.0f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0, 0, 0
};
private float[] params = new float[commands.length];
private static final float mZoomScale = 0.109f;
private static final float mZoomBase = 1.01f;
private int mParam = -1;
private float mIncr = 0;
private Paint mPaint = new Paint();
private float mAspectRatio = 1.0f;
private float mZoom;
// private boolean mPerspectiveCorrection = false;
// private int mTextureMinFilter = GL10.GL_NEAREST;
// private int mTextureMagFilter = GL10.GL_NEAREST;
// Counters for FPS calculation
private boolean mDisplayFPS = false;
private boolean mDisplayCounts = false;
private int mFramesFPS = 10;
private long[] mTimes = new long[mFramesFPS];
private int mTimesIdx = 0;
private Map<String,Message> mMessages = new HashMap<String,Message>();
/**
* Constructs a new GLView.
*/
public GLView() {
mPaint.setColor(0xffffffff);
reset();
}
/**
* Sets the aspect ratio (width/height) of the screen.
*
* @param aspectRatio the screen width divided by the screen height
*/
public void setAspectRatio(float aspectRatio) {
this.mAspectRatio = aspectRatio;
}
/**
* Sets the overall ambient light intensity. This intensity will
* be used to modify the ambient light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_AMBIENT...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setAmbientIntensity(float intensity) {
params[AMBIENT_INTENSITY] = intensity;
}
/**
* Sets the light model ambient intensity. This intensity will be
* used to modify the ambient light value for each of the red,
* green, and blue channels passed to
* glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value
* is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* light model ambient intensity.
*/
public void setLightModelAmbientIntensity(float intensity) {
params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity;
}
/**
* Sets the ambient color for the red, green, and blue channels
* that will be multiplied by the value of setAmbientIntensity and
* passed to glLightfv(...GL_AMBIENT...). The default values are
* {1, 1, 1}.
*
* @param ambient an arry of three floats containing ambient
* red, green, and blue intensity values.
*/
public void setAmbientColor(float[] ambient) {
params[AMBIENT_RED] = ambient[0];
params[AMBIENT_GREEN] = ambient[1];
params[AMBIENT_BLUE] = ambient[2];
}
/**
* Sets the overall diffuse light intensity. This intensity will
* be used to modify the diffuse light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_DIFFUSE...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setDiffuseIntensity(float intensity) {
params[DIFFUSE_INTENSITY] = intensity;
}
/**
* Sets the diffuse color for the red, green, and blue channels
* that will be multiplied by the value of setDiffuseIntensity and
* passed to glLightfv(...GL_DIFFUSE...). The default values are
* {1, 1, 1}.
*
* @param diffuse an array of three floats containing diffuse
* red, green, and blue intensity values.
*/
public void setDiffuseColor(float[] diffuse) {
params[DIFFUSE_RED] = diffuse[0];
params[DIFFUSE_GREEN] = diffuse[1];
params[DIFFUSE_BLUE] = diffuse[2];
}
/**
* Sets the overall specular light intensity. This intensity will
* be used to modify the diffuse light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_SPECULAR...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setSpecularIntensity(float intensity) {
params[SPECULAR_INTENSITY] = intensity;
}
/**
* Sets the specular color for the red, green, and blue channels
* that will be multiplied by the value of setSpecularIntensity and
* passed to glLightfv(...GL_SPECULAR...). The default values are
* {1, 1, 1}.
*
* @param specular an array of three floats containing specular
* red, green, and blue intensity values.
*/
public void setSpecularColor(float[] specular) {
params[SPECULAR_RED] = specular[0];
params[SPECULAR_GREEN] = specular[1];
params[SPECULAR_BLUE] = specular[2];
}
/**
* Returns the current X translation of the modelview
* transformation as passed to glTranslatef. The default value is
* 0.0f.
*
* @return the X modelview translation as a float.
*/
public float getTranslateX() {
return params[TRANSLATE_X];
}
/**
* Returns the current Y translation of the modelview
* transformation as passed to glTranslatef. The default value is
* 0.0f.
*
* @return the Y modelview translation as a float.
*/
public float getTranslateY() {
return params[TRANSLATE_Y];
}
/**
* Returns the current Z translation of the modelview
* transformation as passed to glTranslatef. The default value is
* -50.0f.
*
* @return the Z modelview translation as a float.
*/
public float getTranslateZ() {
return params[TRANSLATE_Z];
}
/**
* Sets the position of the near frustum clipping plane as passed
* to glFrustumf. The default value is 5.0f;
*
* @param nearFrustum the near frustum clipping plane distance as
* a float.
*/
public void setNearFrustum(float nearFrustum) {
params[NEAR_FRUSTUM] = nearFrustum;
}
/**
* Sets the position of the far frustum clipping plane as passed
* to glFrustumf. The default value is 100.0f;
*
* @param farFrustum the far frustum clipping plane distance as a
* float.
*/
public void setFarFrustum(float farFrustum) {
params[FAR_FRUSTUM] = farFrustum;
}
private void computeZoom() {
mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]);
}
/**
* Resets all parameters to their default values.
*/
public void reset() {
for (int i = 0; i < params.length; i++) {
params[i] = defaults[i];
}
computeZoom();
}
private void removeExpiredMessages() {
long now = System.currentTimeMillis();
List<String> toBeRemoved = new ArrayList<String>();
Iterator<String> keyIter = mMessages.keySet().iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
Message msg = mMessages.get(key);
if (msg.getExpirationTime() < now) {
toBeRemoved.add(key);
}
}
Iterator<String> tbrIter = toBeRemoved.iterator();
while (tbrIter.hasNext()) {
String key = tbrIter.next();
mMessages.remove(key);
}
}
/**
* Displays the message overlay on the given Canvas. The
* GLContext.waitGL method should be called prior to calling this
* method. The interactive command display is drawn by this
* method.
*
* @param canvas the Canvas on which messages are to appear.
*/
public void showMessages(Canvas canvas) {
removeExpiredMessages();
float y = 10.0f;
List<String> l = new ArrayList<String>();
l.addAll(mMessages.keySet());
Collections.sort(l);
Iterator<String> iter = l.iterator();
while (iter.hasNext()) {
String key = iter.next();
String text = mMessages.get(key).getText();
canvas.drawText(text, 10.0f, y, mPaint);
y += MESSAGE_Y_SPACING;
}
}
private int mTriangles;
/**
* Sets the number of triangles drawn in the previous frame for
* display by the showStatistics method. The number of triangles
* is not computed by GLView but must be supplied by the
* calling Activity.
*
* @param triangles an Activity-supplied estimate of the number of
* triangles drawn in the previous frame.
*/
public void setNumTriangles(int triangles) {
this.mTriangles = triangles;
}
/**
* Displays statistics on frames and triangles per second. The
* GLContext.waitGL method should be called prior to calling this
* method.
*
* @param canvas the Canvas on which statistics are to appear.
* @param width the width of the Canvas.
*/
public void showStatistics(Canvas canvas, int width) {
long endTime = mTimes[mTimesIdx] = System.currentTimeMillis();
mTimesIdx = (mTimesIdx + 1) % mFramesFPS;
float th = mPaint.getTextSize();
if (mDisplayFPS) {
// Use end time from mFramesFPS frames ago
long startTime = mTimes[mTimesIdx];
String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime));
// Normalize fps to XX.XX format
if (fps.indexOf(".") == 1) {
fps = " " + fps;
}
int len = fps.length();
if (len == 2) {
fps += ".00";
} else if (len == 4) {
fps += "0";
} else if (len > 5) {
fps = fps.substring(0, 5);
}
canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint);
}
if (mDisplayCounts) {
canvas.drawText(mTriangles + " triangles",
width - 100.0f, 10.0f + th + 5, mPaint);
}
}
private void addMessage(String key, String text, int durationMillis) {
long expirationTime = System.currentTimeMillis() + durationMillis;
mMessages.put(key, new Message(text, expirationTime));
}
private void addMessage(String key, String text) {
addMessage(key, text, DEFAULT_DURATION_MILLIS);
}
private void addMessage(String text) {
addMessage(text, text, DEFAULT_DURATION_MILLIS);
}
private void clearMessages() {
mMessages.clear();
}
String command = "";
private void toggleFilter() {
if (params[mParam] == GL10.GL_NEAREST) {
params[mParam] = GL10.GL_LINEAR;
} else {
params[mParam] = GL10.GL_NEAREST;
}
addMessage(commands[mParam],
"Texture " +
(mParam == TEXTURE_MIN_FILTER ? "min" : "mag") +
" filter = " +
(params[mParam] == GL10.GL_NEAREST ?
"nearest" : "linear"));
}
private void togglePerspectiveCorrection() {
if (params[mParam] == GL10.GL_NICEST) {
params[mParam] = GL10.GL_FASTEST;
} else {
params[mParam] = GL10.GL_NICEST;
}
addMessage(commands[mParam],
"Texture perspective correction = " +
(params[mParam] == GL10.GL_FASTEST ?
"fastest" : "nicest"));
}
private String valueString() {
if (mParam == TEXTURE_MIN_FILTER ||
mParam == TEXTURE_MAG_FILTER) {
if (params[mParam] == GL10.GL_NEAREST) {
return "nearest";
}
if (params[mParam] == GL10.GL_LINEAR) {
return "linear";
}
}
if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
if (params[mParam] == GL10.GL_FASTEST) {
return "fastest";
}
if (params[mParam] == GL10.GL_NICEST) {
return "nicest";
}
}
return "" + params[mParam];
}
/**
*
* @return true if the view
*/
public boolean hasMessages() {
return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts;
}
/**
* Process a key stroke. The calling Activity should pass all
* keys from its onKeyDown method to this method. If the key is
* part of a GLView command, true is returned and the calling
* Activity should ignore the key event. Otherwise, false is
* returned and the calling Activity may process the key event
* normally.
*
* @param keyCode the key code as passed to Activity.onKeyDown.
*
* @return true if the key is part of a GLView command sequence,
* false otherwise.
*/
public boolean processKey(int keyCode) {
// Pressing the state key twice enters the UI
// Pressing it again exits the UI
if ((keyCode == STATE_KEY) ||
(keyCode == KeyEvent.KEYCODE_SLASH) ||
(keyCode == KeyEvent.KEYCODE_PERIOD))
{
mState = (mState + 1) % 3;
if (mState == HAVE_NONE) {
clearMessages();
}
if (mState == HAVE_TWO) {
clearMessages();
addMessage("aaaa", "GL", Integer.MAX_VALUE);
addMessage("aaab", "", Integer.MAX_VALUE);
command = "";
}
return true;
} else {
if (mState == HAVE_ONE) {
mState = HAVE_NONE;
return false;
}
}
// If we're not in the UI, exit without handling the key
if (mState != HAVE_TWO) {
return false;
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
command = "";
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
if (command.length() > 0) {
command = command.substring(0, command.length() - 1);
}
} else if (keyCode >= KeyEvent.KEYCODE_A &&
keyCode <= KeyEvent.KEYCODE_Z) {
command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a');
}
addMessage("aaaa", "GL " + command, Integer.MAX_VALUE);
if (command.equals("h")) {
addMessage("aaaa", "GL", Integer.MAX_VALUE);
addMessage("h - help");
addMessage("fn/ff - frustum near/far clip Z");
addMessage("la/lar/lag/lab - abmient intensity/r/g/b");
addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b");
addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b");
addMessage("s - toggle statistics display");
addMessage("tmin/tmag - texture min/mag filter");
addMessage("tpersp - texture perspective correction");
addMessage("tx/ty/tz - view translate x/y/z");
addMessage("z - zoom");
command = "";
return true;
} else if (command.equals("s")) {
mDisplayCounts = !mDisplayCounts;
mDisplayFPS = !mDisplayFPS;
command = "";
return true;
}
mParam = -1;
for (int i = 0; i < commands.length; i++) {
if (command.equals(commands[i])) {
mParam = i;
mIncr = increments[i];
}
}
if (mParam == -1) {
return true;
}
boolean addMessage = true;
// Increment or decrement
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ||
keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
if (mParam == ZOOM_EXPONENT) {
params[mParam] += mIncr;
computeZoom();
} else if ((mParam == TEXTURE_MIN_FILTER) ||
(mParam == TEXTURE_MAG_FILTER)) {
toggleFilter();
} else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
togglePerspectiveCorrection();
} else {
params[mParam] += mIncr;
}
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP ||
keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (mParam == ZOOM_EXPONENT) {
params[mParam] -= mIncr;
computeZoom();
} else if ((mParam == TEXTURE_MIN_FILTER) ||
(mParam == TEXTURE_MAG_FILTER)) {
toggleFilter();
} else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
togglePerspectiveCorrection();
} else {
params[mParam] -= mIncr;
}
}
if (addMessage) {
addMessage(commands[mParam],
labels[mParam] + ": " + valueString());
}
return true;
}
/**
* Zoom in by a given number of steps. A negative value of steps
* zooms out. Each step zooms in by 1%.
*
* @param steps the number of steps to zoom by.
*/
public void zoom(int steps) {
params[ZOOM_EXPONENT] += steps;
computeZoom();
}
/**
* Set the projection matrix using glFrustumf. The left and right
* clipping planes are set at -+(aspectRatio*zoom), the bottom and
* top clipping planes are set at -+zoom, and the near and far
* clipping planes are set to the values set by setNearFrustum and
* setFarFrustum or interactively.
*
* <p> GL side effects:
* <ul>
* <li>overwrites the matrix mode</li>
* <li>overwrites the projection matrix</li>
* </ul>
*
* @param gl a GL10 instance whose projection matrix is to be modified.
*/
public void setProjection(GL10 gl) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
if (mAspectRatio >= 1.0f) {
gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom,
-mZoom, mZoom,
params[NEAR_FRUSTUM], params[FAR_FRUSTUM]);
} else {
gl.glFrustumf(-mZoom, mZoom,
-mZoom / mAspectRatio, mZoom / mAspectRatio,
params[NEAR_FRUSTUM], params[FAR_FRUSTUM]);
}
}
/**
* Set the modelview matrix using glLoadIdentity and glTranslatef.
* The translation values are set interactively.
*
* <p> GL side effects:
* <ul>
* <li>overwrites the matrix mode</li>
* <li>overwrites the modelview matrix</li>
* </ul>
*
* @param gl a GL10 instance whose modelview matrix is to be modified.
*/
public void setView(GL10 gl) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
// Move the viewpoint backwards
gl.glTranslatef(params[TRANSLATE_X],
params[TRANSLATE_Y],
params[TRANSLATE_Z]);
}
/**
* Sets texture parameters.
*
* <p> GL side effects:
* <ul>
* <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li>
* <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li>
* <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li>
* </ul>
*
* @param gl a GL10 instance whose texture parameters are to be modified.
*/
public void setTextureParameters(GL10 gl) {
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
(int)params[TEXTURE_PERSPECTIVE_CORRECTION]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MIN_FILTER,
params[TEXTURE_MIN_FILTER]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
params[TEXTURE_MAG_FILTER]);
}
/**
* Sets the lighting parameters for the given light.
*
* <p> GL side effects:
* <ul>
* <li>sets the GL_LIGHT_MODEL_AMBIENT intensities
* <li>sets the GL_AMBIENT intensities for the given light</li>
* <li>sets the GL_DIFFUSE intensities for the given light</li>
* <li>sets the GL_SPECULAR intensities for the given light</li>
* </ul>
*
* @param gl a GL10 instance whose texture parameters are to be modified.
*/
public void setLights(GL10 gl, int lightNum) {
float[] light = new float[4];
light[3] = 1.0f;
float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY];
light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi;
light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi;
light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi;
gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0);
float ai = params[AMBIENT_INTENSITY];
light[0] = params[AMBIENT_RED]*ai;
light[1] = params[AMBIENT_GREEN]*ai;
light[2] = params[AMBIENT_BLUE]*ai;
gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0);
float di = params[DIFFUSE_INTENSITY];
light[0] = params[DIFFUSE_RED]*di;
light[1] = params[DIFFUSE_GREEN]*di;
light[2] = params[DIFFUSE_BLUE]*di;
gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0);
float si = params[SPECULAR_INTENSITY];
light[0] = params[SPECULAR_RED]*si;
light[1] = params[SPECULAR_GREEN]*si;
light[2] = params[SPECULAR_BLUE]*si;
gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
public class LatLongSphere extends Sphere {
public LatLongSphere(float centerX, float centerY, float centerZ,
float radius, int lats, int longs,
float minLongitude, float maxLongitude,
boolean emitTextureCoordinates,
boolean emitNormals,
boolean emitColors,
boolean flatten) {
super(emitTextureCoordinates, emitNormals, emitColors);
int tris = 2 * (lats - 1) * (longs - 1);
int[] vertices = new int[3 * lats * longs];
int[] texcoords = new int[2 * lats * longs];
int[] colors = new int[4 * lats * longs];
int[] normals = new int[3 * lats * longs];
short[] indices = new short[3 * tris];
int vidx = 0;
int tidx = 0;
int nidx = 0;
int cidx = 0;
int iidx = 0;
minLongitude *= DEGREES_TO_RADIANS;
maxLongitude *= DEGREES_TO_RADIANS;
for (int i = 0; i < longs; i++) {
float fi = (float) i / (longs - 1);
// theta is the longitude
float theta =
(maxLongitude - minLongitude) * (1.0f - fi) + minLongitude;
float sinTheta = (float) Math.sin(theta);
float cosTheta = (float) Math.cos(theta);
for (int j = 0; j < lats; j++) {
float fj = (float) j / (lats - 1);
// phi is the latitude
float phi = PI * fj;
float sinPhi = (float) Math.sin(phi);
float cosPhi = (float) Math.cos(phi);
float x = cosTheta * sinPhi;
float y = cosPhi;
float z = sinTheta * sinPhi;
if (flatten) {
// Place vertices onto a flat projection
vertices[vidx++] = toFixed(2.0f * fi - 1.0f);
vertices[vidx++] = toFixed(0.5f - fj);
vertices[vidx++] = toFixed(0.0f);
} else {
// Place vertices onto the surface of a sphere
// with the given center and radius
vertices[vidx++] = toFixed(x * radius + centerX);
vertices[vidx++] = toFixed(y * radius + centerY);
vertices[vidx++] = toFixed(z * radius + centerZ);
}
if (emitTextureCoordinates) {
texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI)));
texcoords[tidx++] = toFixed(fj);
}
if (emitNormals) {
float norm = 1.0f / Shape.length(x, y, z);
normals[nidx++] = toFixed(x * norm);
normals[nidx++] = toFixed(y * norm);
normals[nidx++] = toFixed(z * norm);
}
// 0 == black, 65536 == white
if (emitColors) {
colors[cidx++] = (i % 2) * 65536;
colors[cidx++] = 0;
colors[cidx++] = (j % 2) * 65536;
colors[cidx++] = 65536;
}
}
}
for (int i = 0; i < longs - 1; i++) {
for (int j = 0; j < lats - 1; j++) {
int base = i * lats + j;
// Ensure both triangles have the same final vertex
// since this vertex carries the color for flat
// shading
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + 1);
indices[iidx++] = (short) (base + lats + 1);
indices[iidx++] = (short) (base + lats);
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + lats + 1);
}
}
allocateBuffers(vertices, texcoords, normals, colors, indices);
}
}
| Java |
/*
* Copyright (C) 2007 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.android.globaltime;
import java.nio.ByteBuffer;
public class Texture {
private ByteBuffer data;
private int width, height;
public Texture(ByteBuffer data, int width, int height) {
this.data = data;
this.width = width;
this.height = height;
}
public ByteBuffer getData() {
return data;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class BrickFactory {
public Brick createBrick(String brickType){
if(brickType == null){
return null;
}
if(brickType.equalsIgnoreCase("SOFT")){
return new SoftBrick();
} else if(brickType.equalsIgnoreCase("MEDIUM")){
return new MediumBrick();
} else if(brickType.equalsIgnoreCase("HARD")){
return new HardBrick();
}
return null;
}
}
| Java |
import javax.swing.*;
import java.awt.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
public class Application extends JFrame {
private static Application instance;
private final int width = 600;
private final int height = 600;
public int highScore;
// Singleton method
public static Application getInstance() {
if (instance == null)
instance = new Application();
return instance;
}
private Application() {
// Setup jframe
this.setSize(new Dimension(width, height));
this.setPreferredSize(new Dimension(width, height));
this.setMinimumSize(new Dimension(width, height));
this.setTitle("Another Brick In the Wall");
this.setLayout(null);
this.setBounds(0, 0, width, height);
//this.setExtendedState(this.getExtendedState() | JFrame.MAXIMIZED_BOTH);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setResizable(true);
}
public static void main(String[] args) {
// Start game on new thread
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
// This will call LogicController constructor.
// Briefly starts the game
GameController.getInstance();
}
});
}
}
| Java |
import java.awt.*;
import java.awt.geom.Ellipse2D;
public class Ball extends Ellipse2D.Double {
float x, y, lastX, lastY;
int width, height;
float xVelocity, yVelocity;
float speed;
int radius;
boolean heatActive;
float velocityConstant;
float heatTimer;
Dimension border;
private GameController logic;
public Ball(Dimension border) {
this.border = border;
logic = GameController.getInstance();
heatTimer = 0;
velocityConstant = 1.0f;
width = 30;
height = 30;
radius = width / 2;
lastX = x;
lastY = y;
xVelocity = speed;
yVelocity = speed;
setFrame(x - width / 2, y - height / 2, width, height);
}
public void update(double delta) {
if(heatTimer > 0) {
heatActive = false;
heatTimer -= delta;
}
setFrame(x - width / 2, y - height / 2, width, height);
//lastX = x;
//lastY = y;
x += xVelocity * delta;
y += yVelocity * delta;
if (x + width / 2 >= border.getSize().getWidth()) {
xVelocity *= -1;
x = (float) border.getWidth() - width / 2;
//yVelocity = yVelocity * 0.95f; // Decrease speed by %5
} else if (x - width / 2 <= 0) {
xVelocity *= -1;
x = width / 2;
}
if (y + height / 2 >= border.getSize().getHeight()) {
// Ball goes down don't struck to below
/*
yVelocity *= -1;
y = (float) border.getHeight() - height/2;
*/
//xVelocity = xVelocity * 0.95f; // Decrease speed by %5
} else if (y - height / 2 <= 0) {
System.out.println(y);
System.out.println(height / 2);
yVelocity *= -1;
y = height / 2;
}
}
public void applyEffect(String type) {
switch (type) {
case "slowerBall":
velocityConstant *= 1.2f;
break;
case "fasterBall":
velocityConstant *= 0.8f;
break;
case "heatBall":
heatTimer = 200;
heatActive = true;
break;
default:
break;
}
}
}
| Java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.Random;
/**
* Created by berkbozkurt on 07/03/15.
*/
/*
LogicController: Singleton
*/
public class GameController {
private Scoreboard scoreboard;
private LifeView lifeView;
private Random powerupGenerator;
private PowerUpFactory powerupFactory;
private boolean gameRunning = true;
private long lastFpsTime;
private boolean paused = false;
private int fps = 60;
private long updateLength = 0;
private boolean running = true;
private static GameController instance;
private GameInteraction gameInteraction;
private GamePanel gamePanel;
private MenuPanel menuPanel;
private int level;
private boolean cheatKeyPressed = false;
// Keys
private boolean upPressed;
private boolean downPressed;
private boolean leftPressed;
private boolean rightPressed;
private int life;
private double elapsedTimeSinceBallsLost;
private boolean hasAnyBall;
private float cheatTimer;
private float powerUpTimer;
private boolean givingPowerUp;
private StateInformation currentState;
// Singleton class so shouldn't be instantiated with new ...
private GameController() {
// Initial state is MenuState
// Just call configureState() after updating the state
MenuState state = new MenuState();
currentState = new StateInformation(state);
state.updateState(currentState);
configureState();
}
public void configureState() {
if (currentState.getState().toString().equalsIgnoreCase("MenuState")) {
menuPanel = new MenuPanel();
menuPanel.setBounds(0, 100, 600, 400);
Application.getInstance().getContentPane().add(menuPanel);
Application.getInstance().getContentPane().setBackground(Color.black);
Application.getInstance().getContentPane().repaint();
Application.getInstance().getContentPane().validate();
} else if (currentState.getState().toString().equalsIgnoreCase("PlayingState")) {
// Remove all previous components from view
Application.getInstance().getContentPane().removeAll();
// Construct InteractionPanel(Ball, Bricks, Player, Surprise objects are in this panel)
life = 3;
level = 1;
powerUpTimer = 0;
cheatTimer = 100;
powerupGenerator = new Random();
powerupFactory = new PowerUpFactory();
gameInteraction = new GameInteraction();
gameRunning = true;
gameInteraction.lastPowerUp = "";
gameInteraction.setLocation(0, 0);
gameInteraction.setOpaque(false);
gameInteraction.setBorder(null);
gameInteraction.setLayout(null);
gameInteraction.constructLevel(level);
scoreboard = new Scoreboard();
scoreboard.setLocation(250, 480);
addKeyBindings(gameInteraction);
// Life View
lifeView = new LifeView();
lifeView.setLocation(5, 15);
for (Ball ball : gameInteraction.getBalls()) {
ball.yVelocity = -2f;
}
Application.getInstance().getContentPane().add(gameInteraction);
Application.getInstance().getContentPane().add(lifeView);
Application.getInstance().getContentPane().add(scoreboard);
gameRunning = true;
paused = false;
// Repaint so changes appear
Application.getInstance().getContentPane().repaint();
Application.getInstance().getContentPane().validate();
// Call Game Loop
runGameLoop();
} else if (currentState.getState().toString().equalsIgnoreCase("WinState")) {
paused = true;
System.out.println("Winstate");
// Check high score
String highScoreString = "Score: ";
if (scoreboard.getScore() < Application.getInstance().highScore) {
highScoreString = "New High Score: ";
}
// Remove all previous components from view
gameRunning = false;
Application.getInstance().getContentPane().removeAll();
System.out.println("WinState");
// All levels finished
JLabel winLabel = new JLabel();
winLabel.setSize(500, 180);
winLabel.setText("<html>Congratulations<br>" + highScoreString + scoreboard.getScore());
winLabel.setLocation(30, 30);
winLabel.setForeground(Color.white);
JButton startGameButton = new JButton();
startGameButton.setText("New Game");
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("resources/game.ttf"));
Font font = Font.createFont(Font.TRUETYPE_FONT, myStream);
Font biggerFont = font.deriveFont(Font.PLAIN, 36f);
winLabel.setFont(biggerFont);
startGameButton.setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
startGameButton.setSize(new Dimension(300, 60));
startGameButton.setForeground(Color.black);
startGameButton.setLocation(winLabel.getX() + 80, 300);
startGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PlayingState playingState = new PlayingState();
playingState.updateState(getCurrentState());
configureState();
}
});
Application.getInstance().getContentPane().add(winLabel);
Application.getInstance().getContentPane().add(startGameButton);
Application.getInstance().getContentPane().repaint();
Application.getInstance().getContentPane().validate();
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("resources/game.ttf"));
Font biggerFont = font.deriveFont(Font.PLAIN, 36f);
winLabel.setFont(biggerFont);
startGameButton.setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
} else if (currentState.getState().toString().equalsIgnoreCase("LoseState")) {
paused = true;
// Check high score
String highScoreString = "Score: ";
if (scoreboard.getScore() < Application.getInstance().highScore) {
highScoreString = "New High Score: ";
}
System.out.println("Lose State");
gameRunning = false;
Application.getInstance().getContentPane().removeAll();
gameInteraction.removeAll();
// All levels finished
JLabel winLabel = new JLabel();
winLabel.setSize(500, 180);
winLabel.setText("<html>Game Over<br>" + highScoreString + scoreboard.getScore());
winLabel.setLocation(30, 30);
winLabel.setForeground(Color.white);
JButton startGameButton = new JButton();
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("resources/game.ttf"));
Font font = Font.createFont(Font.TRUETYPE_FONT, myStream);
Font biggerFont = font.deriveFont(Font.PLAIN, 20f);
winLabel.setFont(biggerFont);
startGameButton.setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
startGameButton.setSize(new Dimension(300, 60));
startGameButton.setText("New Game");
startGameButton.setForeground(Color.black);
startGameButton.setLocation(winLabel.getX() + 80, 300);
startGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
PlayingState playingState = new PlayingState();
playingState.updateState(getCurrentState());
configureState();
}
});
Application.getInstance().getContentPane().add(winLabel);
Application.getInstance().getContentPane().add(startGameButton);
Application.getInstance().getContentPane().repaint();
Application.getInstance().getContentPane().validate();
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("resources/game.ttf"));
Font biggerFont = font.deriveFont(Font.PLAIN, 24f);
winLabel.setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
}else
{
// Throw State exception
}
}
// Use this method to access LogicController
public static GameController getInstance() {
if (instance == null) {
instance = new GameController();
}
return instance;
}
//Starts a new thread and runs the game loop in it.
public void runGameLoop() {
Thread loop = new Thread() {
public void run() {
gameLoop();
}
};
loop.start();
}
public void gameLoop() {
long lastLoopTime = System.nanoTime();
final int TARGET_FPS = 120;
final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
// keep looping round til the game ends
while (gameRunning) {
// work out how long its been since the last update, this
// will be used to calculate how far the entities should
// move this loop
long now = System.nanoTime();
updateLength = now - lastLoopTime;
lastLoopTime = now;
double delta = updateLength / ((double) OPTIMAL_TIME);
// update the frame counter
lastFpsTime += updateLength;
fps++;
// update our FPS counter if a second has passed since
// we last recorded
if (lastFpsTime >= 1000000000) {
System.out.println("(FPS: " + fps + ")");
gameInteraction.fps = fps;
lastFpsTime = 0;
fps = 0;
}
// update the game logic
doGameUpdates(delta);
// draw everything
render();
// we want each frame to take 10 milliseconds, to do this
// we've recorded when we started the frame. We add 10 milliseconds
// to this and then factor in the current time to give
// us our final value to wait for
// remember this is in ms, whereas our lastLoopTime etc. vars are in ns.
try {
//
Thread.sleep((Math.abs(lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000));
//Thread.sleep(Math.abs((lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000));
} catch (InterruptedException e) {
//e.printStackTrace();
}
}
}
private void render() {
gameInteraction.repaint();
scoreboard.repaint();
lifeView.repaint();
}
// Game play Logic
private void doGameUpdates(double delta) {
if (!paused) {
Paddle paddle = gameInteraction.getPaddle();
// Paddle and powerUps Collision
for (int i = 0; i < gameInteraction.getPowerUps().size(); i++) {
PowerUp powerUp = gameInteraction.getPowerUps().get(i);
if (powerUp.intersects(paddle)) {
if (powerUp.getTargetClassName().equals(Paddle.class.getName())) {
if (powerUp.getType().equals("Longer Paddle"))
gameInteraction.createPaddle("default");
else if (powerUp.getType().equals("Shorter Paddle"))
gameInteraction.createPaddle("shorter");
} else if (powerUp.getTargetClassName().equals(Ball.class.getName())) {
if (powerUp.getType().equals("Triple Ball")) {
Ball newBall = null;
Ball newBall2 = null;
for (Ball ball : gameInteraction.getBalls()) {
newBall = new Ball(gameInteraction.getSize());
newBall.xVelocity = (float) (Math.random() - 0.5) * 5.0f;
newBall.yVelocity = -2;
newBall.x = ball.x;
newBall.y = ball.y;
newBall2 = new Ball(gameInteraction.getSize());
newBall2.xVelocity = (float) (Math.random() - 0.5) * 5.0f;
newBall2.yVelocity = -2;
newBall2.x = ball.x;
newBall2.y = ball.y;
}
if (newBall != null) {
gameInteraction.getBalls().add(newBall);
gameInteraction.getBalls().add(newBall2);
}
} else {
for (Ball ball : gameInteraction.getBalls()) {
ball.applyEffect(powerUp.getType());
}
}
}
gameInteraction.destroyPowerUp(i);
}
}
// Balls and Paddle Collision
for (Ball ball : gameInteraction.getBalls()) {
if (ball.intersects(paddle) && ball.yVelocity > 0) {
ball.yVelocity = ball.yVelocity * -1;
ball.xVelocity = paddle.xVelocity * (float) Math.random();
}
}
// Ensure doesn't create powerUp more than once
if (givingPowerUp) {
powerUpTimer += delta;
if (powerUpTimer > 200) {
givingPowerUp = false;
powerUpTimer = 0;
}
}
// Balls and Brick Collision
for (int i = 0; i < gameInteraction.getBricks().size(); i++) {
for (Ball ball : gameInteraction.getBalls()) {
Brick brick = gameInteraction.getBricks().get(i);
brick.update();
Rectangle brickRect = (Rectangle) brick;
if (ball.intersects(brickRect)) {
// Handle score
if (brick instanceof SoftBrick) {
scoreboard.addScore(80);
} else if (brick instanceof MediumBrick) {
scoreboard.addScore(120);
} else {
scoreboard.addScore(150);
}
// Generate PowerUp by %30 chance
if (powerUpTimer <= 0 && !givingPowerUp) {
givingPowerUp = true;
int randomNum = powerupGenerator.nextInt(10);
if (randomNum > 0) {
PowerUp powerup = powerupFactory.createPowerUp(
(int) (((Rectangle) brick).getFrame().getX() + ((Rectangle) brick).getWidth() / 2),
(int) (((Rectangle) brick).getFrame().getY() + ((Rectangle) brick).getHeight() / 2));
gameInteraction.getPowerUps().add(powerup);
gameInteraction.lastPowerUp = powerup.getType();
}
}
ball.yVelocity *= -1;
// Add bricks that has 0 life to destroyable ArrayList
// TODO:
gameInteraction.destroyBrick(i);
}
}
}
// Update powerUps speed according to delta time
for (PowerUp powerUp : gameInteraction.getPowerUps()) {
powerUp.update(delta);
}
// Update ball and player according to delta time
for (int i = 0; i < gameInteraction.getBalls().size(); i++) {
Ball ball = gameInteraction.getBalls().get(i);
ball.update(delta);
// Limit balls max speed
if (ball.xVelocity >= 8) {
ball.xVelocity = 8 * (float) delta;
}
if (ball.yVelocity >= 4) {
ball.yVelocity = 8 * (float) delta;
}
// If ball is in screen and moving
if (ball.y - 40 < gameInteraction.getHeight() && !(ball.xVelocity == 0 && ball.yVelocity == 0)) {
hasAnyBall = true;
}
// Ball is not in screen
if (ball.y - 40 > gameInteraction.getHeight()) {
System.out.println("Destroy ball");
gameInteraction.destroyBall(i);
}
}
// Increment timer (Time to start the ball after going down)
if (gameInteraction.getBalls().size() == 0 && !hasAnyBall) {
Ball ball = new Ball(gameInteraction.getSize());
ball.xVelocity = 0;
ball.yVelocity = 0;
ball.x = gameInteraction.getWidth() / 2;
ball.y = gameInteraction.getHeight() / 2;
gameInteraction.getBalls().add(ball);
}
if (!hasAnyBall) {
elapsedTimeSinceBallsLost += delta;
}
//if (!hasAnyBall && )
paddle.update(delta);
// If timer exceeds 200 start the ball with random velocity
if (elapsedTimeSinceBallsLost > 200) {
System.out.println("ball start");
for (Ball ball : gameInteraction.getBalls()) {
ball.xVelocity = ((float) Math.random() - 0.5f) * 4.0f;
ball.yVelocity = 2.0f;
hasAnyBall = true;
elapsedTimeSinceBallsLost = 0;
}
}
// Cheat
if (cheatKeyPressed && hasAnyBall) {
cheatTimer -= delta;
if (cheatTimer < 0) {
PowerUp powerUp = powerupFactory.createTripleBall(
(int) gameInteraction.getBalls().get(0).getX(),
(int) gameInteraction.getBalls().get(0).getY());
gameInteraction.getPowerUps().add(powerUp);
cheatTimer = 100;
}
}
if (gameInteraction.getBricks().size() == 0) {
System.out.println("Next level");
++level;
// next level
// Remove Balls
for (int i = 0; i < gameInteraction.getBalls().size(); i++) {
gameInteraction.destroyBall(i);
}
for (int i = 0; i < gameInteraction.getPowerUps().size(); i++) {
gameInteraction.destroyPowerUp(i);
}
// Construct level
gameInteraction.getBalls().clear();
if (level < 4) {
gameInteraction.constructLevel(level);
} else {
WinState state = new WinState();
currentState = new StateInformation(state);
configureState();
}
// Add new ball
Ball ball = new Ball(gameInteraction.getSize());
ball.xVelocity = 0;
ball.yVelocity = 0;
ball.x = gameInteraction.getWidth() / 2;
ball.y = gameInteraction.getHeight() / 2;
gameInteraction.getBalls().add(ball);
hasAnyBall = false;
// Add new ball by setting hasAnyBall to false
}
// Delete all game objects that added to destroyable ArrayList
gameInteraction.removeDestroyedBricks();
gameInteraction.removeDestroyedBalls();
gameInteraction.removeDestroyedPowerUps();
if (gameInteraction.getBalls().size() == 0) {
gameInteraction.createPaddle("default");
hasAnyBall = false;
life--;
lifeView.decreaseLife();
if (life == 0) {
LoseState state = new LoseState();
currentState = new StateInformation(state);
configureState();
}
}
}
}
public static void addKeyBindings(JComponent jc) {
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "Up pressed");
jc.getActionMap().put("Up pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setUpPressed(true);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "Up released");
jc.getActionMap().put("Up released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setUpPressed(false);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "Down pressed");
jc.getActionMap().put("Down pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setDownPressed(true);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "Down released");
jc.getActionMap().put("Down released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setDownPressed(false);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "Left pressed");
jc.getActionMap().put("Left pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setLeftPressed(true);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, true), "Left released");
jc.getActionMap().put("Left released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setLeftPressed(false);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "Right pressed");
jc.getActionMap().put("Right pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setRightPressed(true);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, true), "Right released");
jc.getActionMap().put("Right released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setRightPressed(false);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0, false), "Q pressed");
jc.getActionMap().put("Q pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setCheatKeyPressed(true);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_Q, 0, true), "Q released");
jc.getActionMap().put("Q released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().setCheatKeyPressed(false);
}
});
jc.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "ESC pressed");
jc.getActionMap().put("ESC pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
GameController.getInstance().pauseGame();
}
});
}
public StateInformation getCurrentState() {
return currentState;
}
public void setCurrentState(StateInformation currentState) {
this.currentState = currentState;
}
// Accessor methods
public boolean isUpPressed() {
return upPressed;
}
public void setUpPressed(boolean upPressed) {
this.upPressed = upPressed;
}
public boolean isDownPressed() {
return downPressed;
}
public void setDownPressed(boolean downPressed) {
this.downPressed = downPressed;
}
public boolean isLeftPressed() {
return leftPressed;
}
public void setLeftPressed(boolean leftPressed) {
this.leftPressed = leftPressed;
}
public boolean isRightPressed() {
return rightPressed;
}
public void setRightPressed(boolean rightPressed) {
this.rightPressed = rightPressed;
}
public void setCheatKeyPressed(boolean b) {
this.cheatKeyPressed = b;
}
public void pauseGame() {
if (paused) paused = false;
else paused = true;
}
}
| Java |
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class SoftBrick extends Rectangle implements Brick {
private Dimension size;
private int life;
private Point location;
public SoftBrick() {
super();
life = 1;
width = 100;
height = 40;
location = new Point();
}
@Override
public void setLocation(int x, int y) {
location.x = x;
location.y = y;
}
@Override
public Point getLocation() {
return location;
}
@Override
public BufferedImage getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/softBrick.png"));
}
catch (IOException e) {
e.printStackTrace();
}
return img;
}
@Override
public Dimension getSize() {return size; }
@Override
public void setSize(Dimension size) {
this.size = size;
}
@Override
public void update() {
setFrame(location.x, location.y, size.getWidth(), size.getHeight());
}
@Override
public void decreaseLife() {
life--;
}
@Override
public int getLife() {
return life;
}
@Override
public void destroyBrick() {
life = 0;
}
}
| Java |
import java.awt.*;
import java.util.ArrayList;
import java.util.Vector;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class LevelManager {
private int level;
private Dimension size;
private BrickFactory brickFactory;
public LevelManager(Dimension size) {
level = 1;
this.size = size;
brickFactory = new BrickFactory();
}
public Vector<Brick> constructLevel(int level) {
// Rows
Vector<Brick> bricks = new Vector<>();
int x = 0;
int y = 0;
int brickWidth = 0;
int brickHeight = 0;
int numberOfBricksInColumn = 0;
int numberOfBricksInRow = 0;
int xSpaceBetweenBricks = 0;
int ySpaceBetweenBricks = 0;
String brickType = null;
if (level == 1) {
brickType = "SOFT";
brickWidth = 100;
brickHeight = 40;
numberOfBricksInColumn =3;
numberOfBricksInRow = 3;
xSpaceBetweenBricks = (size.width - (numberOfBricksInRow * brickWidth)) / (numberOfBricksInRow + 1);
ySpaceBetweenBricks = (size.height/2 - (numberOfBricksInColumn * brickHeight)) / (numberOfBricksInColumn + 1);
}
else if(level == 2) {
brickType = "MEDIUM";
brickWidth = 100;
brickHeight = 30;
numberOfBricksInColumn = 3;
numberOfBricksInRow = 3;
xSpaceBetweenBricks = (size.width - (numberOfBricksInRow * brickWidth)) / (numberOfBricksInRow + 1);
ySpaceBetweenBricks = (size.height/2 - (numberOfBricksInColumn * brickHeight)) / (numberOfBricksInColumn + 1);
}
else if(level == 3) {
brickType = "HARD";
brickWidth = 40;
brickHeight = 10;
numberOfBricksInColumn = 3;
numberOfBricksInRow = 3;
xSpaceBetweenBricks = (size.width - (numberOfBricksInRow * brickWidth)) / (numberOfBricksInRow + 1);
ySpaceBetweenBricks = (size.height/2 - (numberOfBricksInColumn * brickHeight)) / (numberOfBricksInColumn + 1);
}
else {
// Give exception (Wrong Input)
return null;
}
// Rows 1....4
for (int i = 0; i < numberOfBricksInColumn; i++) {
// Columns 1...10
for (int j = 0; j < numberOfBricksInRow; j++) {
// Adjust location of brick
x = (xSpaceBetweenBricks * (i + 1)) + (i * brickWidth);
y = (ySpaceBetweenBricks * (j + 1)) + (j * brickHeight);
// Create brick
Brick brick = brickFactory.createBrick(brickType);
brick.setSize(new Dimension(brickWidth, brickHeight));
brick.setLocation(x, y);
bricks.add(brick);
}
}
return bricks;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class LoseState implements State {
@Override
public void updateState(StateInformation state) {
state.setState(this);
}
public String toString() {
return "LoseState";
}
} | Java |
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class PowerUp extends Rectangle2D.Double{
float x, y;
float xVelocity, yVelocity;
private String imageURL;
private String targetClassName;
private String type;
// Constructor
public PowerUp(int x, int y, String type) {
// Location & velocity
width = 42;
height = 42;
this.x = x;
this.y = y;
this.xVelocity = 0;
this.yVelocity = 2;
setFrame(x-width/2, y-height/2, width, height);
// Set type of powerup
this.type = type;
// PowerUp Image Handler
switch(type) {
case "Longer Paddle":
targetClassName = Paddle.class.getName();
imageURL = "";
break;
case "Shorter Paddle":
targetClassName = Paddle.class.getName();
imageURL = "";
break;
case "Faster Paddle":
targetClassName = Paddle.class.getName();
imageURL = "";
break;
case "Slower Paddle":
targetClassName = Paddle.class.getName();
imageURL = "";
break;
case "Faster Ball":
targetClassName = Ball.class.getName();
imageURL = "";
break;
case "Slower Ball":
targetClassName = Ball.class.getName();
imageURL = "";
break;
case "Triple Ball":
targetClassName = Ball.class.getName();
imageURL = "";
break;
default:
imageURL = "";
break;
}
imageURL = "resources/star.png";
}
public String getType() {
return type;
}
public String getTargetClassName() {
return targetClassName;
}
public BufferedImage getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(new File(imageURL));
}
catch (IOException e) {
System.out.println("Can't find img");
e.printStackTrace();
}
return img;
}
public void update(double delta) {
setFrame(x-width/2, y-height/2, width, height);
//lastX = x;
//lastY = y;
x += xVelocity * delta;
y += yVelocity * delta;
}
}
| Java |
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by BerkBozkurt on 14.5.2015.
*/
public class LifeView extends JPanel {
private int life;
private BufferedImage heart;
public LifeView() {
super();
life = 3;
setVisible(true);
setSize(66, 22);
setOpaque(false);
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/heartIcon.png"));
} catch (IOException e) {
System.out.println("Cant find img");
e.printStackTrace();
}
heart = img;
}
public void addLife() {
life++;
}
public void decreaseLife() {
life--;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < life; i++) {
g.drawImage(heart, (i) * 22, 3, null); // see javadoc for more info on the parameters
}
}
}
| Java |
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class GamePanel extends JPanel {
private JTextArea scoreField;
private JTextArea lifeField;
private int score;
private int life;
public GamePanel() {
this.score = 0;
this.life = 3;
this.setBackground(Color.BLACK);
}
public void increaseScore(int score) {
this.score += score;
scoreField.setText(String.format("%i", this.score));
}
public void decreaseLife() {
this.life--;
lifeField.setText(String.format("%i", this.life));
}
public void increaseLife() {
this.life++;
lifeField.setText(String.format("%i", this.life));
}
}
| Java |
import javax.swing.*;
import java.awt.*;
import java.io.*;
/**
* Created by BerkBozkurt on 14.5.2015.
*/
public class Scoreboard extends JLabel{
private int score;
public Scoreboard() {
super();
this.setSize(140, 60);
this.setOpaque(false);
this.setVisible(true);
this.setForeground(Color.white);
score = 0;
try {
InputStream myStream = new BufferedInputStream(new FileInputStream("resources/game.ttf"));
Font font = Font.createFont(Font.TRUETYPE_FONT, myStream);
Font biggerFont = font.deriveFont(Font.PLAIN, 20f);
setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
setText(String.format("%05d", score));
}
public void addScore(int score) {
this.score += score;
setText(String.format("%05d", this.score));
}
public void setScore(int i) {
score = 0;
setText(String.format("%05d", score));
}
public int getScore() {
return score;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class StateInformation {
// State variable
private State state;
// Constructor
public StateInformation(State state) {
this.state = state;
}
// Getter and setter
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class MenuState implements State {
@Override
public void updateState(StateInformation state) {
state.setState(this);
}
public String toString() {
return "MenuState";
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class WinState implements State {
@Override
public void updateState(StateInformation state) {
state.setState(this);
}
public String toString() {
return "WinState";
}
} | Java |
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.util.Vector;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class GameInteraction extends JPanel {
private LifeView lifeView;
// Single paddle object
private Paddle paddle;
// Game Object Containers
private Vector<Ball> balls;
public float fps;
public String lastPowerUp;
private Vector<Brick> bricks;
private Vector<PowerUp> powerUps;
private Vector<Brick> destroyedBricks;
private Vector<Ball> destroyedBalls;
private Vector<PowerUp> destroyedPowerups;
// Controllers
private LevelManager levelManager;
private GameController gameController;
// Constructor
public GameInteraction() {
// View Construction
this.setMaximumSize(new Dimension(600, 550));
this.setSize(new Dimension(600, 550));
this.setMinimumSize(new Dimension(600, 550));
this.setPreferredSize(new Dimension(600, 550));
this.setBackground(Color.BLACK);
// Initiate Brick and Ball ArrayList
bricks = new Vector<Brick>();
balls = new Vector<Ball>();
powerUps = new Vector<PowerUp>();
destroyedBricks = new Vector<Brick>();
destroyedBalls = new Vector<Ball>();
destroyedPowerups = new Vector<PowerUp>();
// Create Ball
Ball ball = new Ball(this.getSize());
ball.x = 300;
ball.y = 400;
ball.xVelocity = 0f;
ball.yVelocity = -2f;
// Add the first ball to container
balls.add(ball);
// Create Paddle
paddle = new Paddle(this.getSize(), "default");
paddle.x = this.getWidth() / 2 - paddle.width / 2;
paddle.y = this.getHeight() - paddle.height;
// Create Level Manager
levelManager = new LevelManager(this.getSize());
// Get GameController
gameController = GameController.getInstance();
// Update views
this.validate();
this.repaint();
}
public void createPaddle(String type) {
float x = paddle.x;
float y = paddle.y;
paddle = new Paddle(this.getSize(), type);
paddle.x = x;
paddle.y = y;
}
public void destroyBrick(int i) {
destroyedBricks.add(bricks.get(i));
}
public void destroyBall(int i) {
destroyedBalls.add(balls.get(i));
}
public void destroyPowerUp(int i) {
destroyedPowerups.add(powerUps.get(i));
}
public void removeDestroyedBricks() {
for (Brick b : destroyedBricks) {
bricks.remove(b);
}
destroyedBricks.clear();
}
public void removeDestroyedBalls() {
for (Ball b : destroyedBalls) {
balls.remove(b);
}
destroyedBalls.clear();
}
public void removeDestroyedPowerUps() {
for (PowerUp p: destroyedPowerups) {
powerUps.remove(p);
}
destroyedPowerups.clear();
}
public void constructLevel(int level) {
for (Ball b : destroyedBalls) {
b.yVelocity = -2f;
}
bricks.addAll(levelManager.constructLevel(level));
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// Paint Ball
g.setColor(Color.WHITE);
for(Ball b : balls) {
g.fillOval((int) (b.x - b.width / 2), (int) (b.y - b.height / 2), b.width, b.height);
}
// Paint Paddle
g.setColor(Color.BLACK);
g.drawImage(paddle.getImage(), (int) (paddle.x - paddle.width / 2), (int) (paddle.y - paddle.height / 2), null);
for(Brick b : bricks) {
g.drawImage(b.getImage(), b.getLocation().x, b.getLocation().y, null);
}
for(PowerUp p : powerUps) {
g.drawImage(p.getImage(), (int) p.getX(), (int)p.getY(), null);
}
g.setColor(Color.WHITE);
if(fps != 0) {
g.drawString("FPS: " + fps, 15, 10);
}
g.drawString(lastPowerUp, 80, 10);
g.dispose();
}
public Vector<PowerUp> getPowerUps() { return powerUps; }
public Vector<Ball> getBalls() { return balls; }
public Paddle getPaddle() { return paddle; }
public Vector<Brick> getBricks() {
return bricks;
}
public LifeView getLifeView() {return lifeView; }
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public interface Subject {
public void registerObserver(Observer observer);
public void notifyObserver();
public void unRegisterObserver(Observer observer);
public Object getUpdate();
} | Java |
import java.awt.*;
import java.awt.image.BufferedImage;
/**
* Created by berkbozkurt on 07/03/15.
*/
public interface Brick {
// Methods
BufferedImage getImage();
void setLocation(int x, int y);
Point getLocation();
Dimension getSize();
void setSize(Dimension size);
void update();
int getLife();
void decreaseLife();
void destroyBrick();
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class PlayingState implements State {
@Override
public void updateState(StateInformation state) {
state.setState(this);
}
public String toString() {
return "PlayingState";
}
}
| Java |
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class MenuPanel extends JPanel {
private JButton startGameButton;
private JButton settingsGameButton;
private JButton quitGameButton;
public MenuPanel() {
setBackground(Color.black);
// Initial setup
startGameButton = new JButton("Start Game");
startGameButton.setSize(new Dimension(500, 100));
startGameButton.setForeground(Color.black);
// Center the startGameButton
startGameButton.setLocation(
(Application.getInstance().getWidth() / 2) - (this.getWidth() / 2),
((Application.getInstance().getHeight() / 2) - (this.getHeight() / 2) ) * 1 / 4);
settingsGameButton = new JButton("Settings");
settingsGameButton.setSize(new Dimension(500, 100));
settingsGameButton.setForeground(Color.black);
// Center the startGameButton
settingsGameButton.setLocation(
(Application.getInstance().getWidth() / 2) - (this.getWidth() / 2),
((Application.getInstance().getHeight() / 2) - (this.getHeight() / 2)) * 2 / 4);
quitGameButton = new JButton("Quit");
quitGameButton.setSize(new Dimension(500, 100));
quitGameButton.setForeground(Color.black);
// Center the startGameButton
quitGameButton.setLocation(
(Application.getInstance().getWidth() / 2) - (this.getWidth() / 2),
((Application.getInstance().getHeight() / 2) - (this.getHeight() / 2)) * 3 / 4);
// Set font
try {
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("resources/game.ttf"));
Font biggerFont = font.deriveFont(Font.PLAIN, 48f);
startGameButton.setFont(biggerFont);
settingsGameButton.setFont(biggerFont);
quitGameButton.setFont(biggerFont);
} catch (IOException | FontFormatException ex) {
ex.printStackTrace();
}
this.add(startGameButton);
this.add(settingsGameButton);
this.add(quitGameButton);
this.validate();
this.repaint();
// Player started the game
startGameButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
// Get logicController instance
GameController logic = GameController.getInstance();
// Create playing state and update it
PlayingState playingState = new PlayingState();
playingState.updateState(logic.getCurrentState());
logic.configureState();
}
});
}
}
| Java |
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by berkbozkurt on 08/03/15.
*/
public class Paddle extends Rectangle {
float x, y, lastX, lastY;
int width, height;
float xVelocity, yVelocity;
float speed;
float velocityConstant;
Dimension border;
private GameController logic;
BufferedImage image;
BufferedImage doubledImage;
BufferedImage halvedImage;
BufferedImage originalImage;
boolean doubled;
boolean halfed;
public void paintComponent(Graphics g) {
}
public Paddle(Dimension border, String type)
{
doubled = false;
halfed = false;
logic = GameController.getInstance();
this.border = border;
if(type.equals("long")) {
width = 150;
}
else if(type.equals("default")) {
width = 100;
}
else {
width = 75;
}
height = 20;
lastX = x;
lastY = y;
xVelocity = speed;
yVelocity = speed;
velocityConstant = 1;
setFrame(x-width/2, y-height/2, width, height);
// Load images in constructor
image = loadImage(type);
}
public void update(double delta)
{
setFrame(x-width/2, y-height/2, width, height);
if(logic.isUpPressed()) {
yVelocity = -2f;
}
if(logic.isDownPressed()) {
yVelocity = 2f;
}
if(!logic.isDownPressed() && !logic.isUpPressed()) {
yVelocity = 0;
}
if(logic.isRightPressed()) {
xVelocity = 2f;
}
if(logic.isLeftPressed()) {
xVelocity = -2f;
}
if(!logic.isRightPressed() && !logic.isLeftPressed()) {
xVelocity = 0;
}
lastX = x;
lastY = y;
x += velocityConstant * xVelocity * delta;
y += velocityConstant * yVelocity * delta;
if (x + width/2 >= border.getSize().getWidth())
{
xVelocity = 0;
x = (float) border.getWidth() - width/2;
//yVelocity = yVelocity * 0.95f; // Decrease speed by %5
}
else if (x - width/2 <= 0)
{
xVelocity = 0;
x = width/2;
}
if (y + height/2 >= border.getSize().getHeight())
{
yVelocity = 0;
y = (float) border.getHeight() - height/2;
//xVelocity = xVelocity * 0.95f; // Decrease speed by %5
}
else if (y - height/2 <= border.getSize().getHeight() * 0.6)
{
yVelocity = 0;
y = (float) border.getSize().getHeight() * 0.6f + height/2;
}
}
public BufferedImage getImage() {
if(halfed)
return halvedImage;
else if(doubled)
return doubledImage;
return image;
}
public BufferedImage loadImage(String type) {
String path = null;
if(type.equals("long"))
path = "resources/longerPlayer.png";
else if(type.equals("default")) {
path = "resources/player.png";
}
else {
path = "resources/playerHalf.png";
}
BufferedImage img = null;
try {
img = ImageIO.read(new File(path));
} catch (IOException e) {
System.out.println("Cant find img");
e.printStackTrace();
}
return img;
}
public void applyEffect(String type) {
switch(type) {
case "fasterPaddle":
velocityConstant *= 1.2f;
break;
case "slowerPaddle":
if(velocityConstant > 0.4f)
velocityConstant *= 0.8f;
break;
case "paddleGun":
break;
case "magnetizedPaddle":
break;
case "invertedPaddle":
break;
default:
break;
}
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public interface Observer {
public void update();
public void setSubject(Subject subject);
}
| Java |
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class MediumBrick extends Rectangle implements Brick {
private Point location;
private Dimension size;
private int life;
public MediumBrick() {
super();
life = 2;
location = new Point();
width = 100;
height = 30;
}
@Override
public void setLocation(int x, int y) {
location.x = x;
location.y = y;
}
@Override
public Point getLocation() {
return location;
}
@Override
public BufferedImage getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/mediumBrick.png"));
} catch (IOException e) {
e.printStackTrace();
}
return img;
}
@Override
public Dimension getSize() {
return size;
}
@Override
public void setSize(Dimension size) {
this.size = size;
}
@Override
public void update() {
setFrame(location.x, location.y, size.getWidth(), size.getHeight());
}
@Override
public void decreaseLife() {
life--;
}
@Override
public int getLife() {
return life;
}
@Override
public void destroyBrick() {
life = 0;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public interface State {
public void updateState(StateInformation state);
}
| Java |
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* Created by berkbozkurt on 07/03/15.
*/
public class HardBrick extends Rectangle implements Brick {
private Point location;
private int life;
private Dimension size;
public HardBrick() {
super();
location = new Point();
life = 1;
width = 40;
height = 40;
}
@Override
public void setLocation(int x, int y) {
location.x = x;
location.y = y;
}
@Override
public Point getLocation() {
return location;
}
@Override
public BufferedImage getImage() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("resources/hardBrick.png"));
}
catch (IOException e) {
System.out.println("Can't find img");
e.printStackTrace();
}
return img;
}
@Override
public Dimension getSize() {return size; }
@Override
public void setSize(Dimension size) {
this.size = size;
}
@Override
public void update() {
setFrame(location.x,location.y,size.getWidth(), size.getHeight());
}
@Override
public void decreaseLife() {
life--;
}
@Override
public int getLife() {
return life;
}
@Override
public void destroyBrick() {
life = 0;
}
}
| Java |
/**
* Created by berkbozkurt on 07/03/15.
*/
public class GameOverState implements State {
@Override
public void updateState(StateInformation state) {
state.setState(this);
}
public String toString() {
return "GameOverState";
}
} | Java |
import java.util.Random;
/**
* Created by BerkBozkurt on 10.5.2015.
*/
public class PowerUpFactory {
private int POWERUP_SIZE = 7;
public PowerUp createPowerUp(int x, int y){
Random rand = new Random();
int randomNum = rand.nextInt(POWERUP_SIZE) + 1;
String powerUpType;
switch(randomNum) {
case 1:
powerUpType = "Longer Paddle";
break;
case 2:
powerUpType = "Shorter Paddle";
break;
case 3:
powerUpType = "Faster Paddle";
break;
case 4:
powerUpType = "Slower Paddle";
break;
case 5:
powerUpType = "Faster Ball";
break;
case 6:
powerUpType = "Slower Ball";
break;
case 7:
powerUpType = "Triple Ball";
break;
default:
powerUpType = "longerPaddle";
break;
}
return new PowerUp(x, y, powerUpType);
}
public PowerUp createTripleBall(int x, int y) {
PowerUp p = new PowerUp(x, y, "Triple Ball");
return p;
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* An {@link OutputStream} that starts buffering to a byte array, but
* switches to file buffering once the data reaches a configurable size.
*
* <p>This class is thread-safe.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class FileBackedOutputStream extends OutputStream {
private final int fileThreshold;
private final boolean resetOnFinalize;
private final InputSupplier<InputStream> supplier;
private OutputStream out;
private MemoryOutput memory;
private File file;
/** ByteArrayOutputStream that exposes its internals. */
private static class MemoryOutput extends ByteArrayOutputStream {
byte[] getBuffer() {
return buf;
}
int getCount() {
return count;
}
}
/** Returns the file holding the data (possibly null). */
@VisibleForTesting synchronized File getFile() {
return file;
}
/**
* Creates a new instance that uses the given file threshold, and does
* not reset the data when the {@link InputSupplier} returned by
* {@link #getSupplier} is finalized.
*
* @param fileThreshold the number of bytes before the stream should
* switch to buffering to a file
*/
public FileBackedOutputStream(int fileThreshold) {
this(fileThreshold, false);
}
/**
* Creates a new instance that uses the given file threshold, and
* optionally resets the data when the {@link InputSupplier} returned
* by {@link #getSupplier} is finalized.
*
* @param fileThreshold the number of bytes before the stream should
* switch to buffering to a file
* @param resetOnFinalize if true, the {@link #reset} method will
* be called when the {@link InputSupplier} returned by {@link
* #getSupplier} is finalized
*/
public FileBackedOutputStream(int fileThreshold, boolean resetOnFinalize) {
this.fileThreshold = fileThreshold;
this.resetOnFinalize = resetOnFinalize;
memory = new MemoryOutput();
out = memory;
if (resetOnFinalize) {
supplier = new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return openStream();
}
@Override protected void finalize() {
try {
reset();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
};
} else {
supplier = new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return openStream();
}
};
}
}
/**
* Returns a supplier that may be used to retrieve the data buffered
* by this stream.
*/
public InputSupplier<InputStream> getSupplier() {
return supplier;
}
private synchronized InputStream openStream() throws IOException {
if (file != null) {
return new FileInputStream(file);
} else {
return new ByteArrayInputStream(
memory.getBuffer(), 0, memory.getCount());
}
}
/**
* Calls {@link #close} if not already closed, and then resets this
* object back to its initial state, for reuse. If data was buffered
* to a file, it will be deleted.
*
* @throws IOException if an I/O error occurred while deleting the file buffer
*/
public synchronized void reset() throws IOException {
try {
close();
} finally {
if (memory == null) {
memory = new MemoryOutput();
} else {
memory.reset();
}
out = memory;
if (file != null) {
File deleteMe = file;
file = null;
if (!deleteMe.delete()) {
throw new IOException("Could not delete: " + deleteMe);
}
}
}
}
@Override public synchronized void write(int b) throws IOException {
update(1);
out.write(b);
}
@Override public synchronized void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override public synchronized void write(byte[] b, int off, int len)
throws IOException {
update(len);
out.write(b, off, len);
}
@Override public synchronized void close() throws IOException {
out.close();
}
@Override public synchronized void flush() throws IOException {
out.flush();
}
/**
* Checks if writing {@code len} bytes would go over threshold, and
* switches to file buffering if so.
*/
private void update(int len) throws IOException {
if (file == null && (memory.getCount() + len > fileThreshold)) {
File temp = File.createTempFile("FileBackedOutputStream", null);
if (resetOnFinalize) {
// Finalizers are not guaranteed to be called on system shutdown;
// this is insurance.
temp.deleteOnExit();
}
FileOutputStream transfer = new FileOutputStream(temp);
transfer.write(memory.getBuffer(), 0, memory.getCount());
transfer.flush();
// We've successfully transferred the data; switch to writing to file
out = transfer;
file = temp;
memory = null;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import java.io.Closeable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Utility methods for working with {@link Closeable} objects.
*
* @author Michael Lancaster
* @since 1.0
*/
@Beta
public final class Closeables {
@VisibleForTesting static final Logger logger
= Logger.getLogger(Closeables.class.getName());
private Closeables() {}
/**
* Closes a {@link Closeable}, with control over whether an
* {@code IOException} may be thrown. This is primarily useful in a
* finally block, where a thrown exception needs to be logged but not
* propagated (otherwise the original exception will be lost).
*
* <p>If {@code swallowIOException} is true then we never throw
* {@code IOException} but merely log it.
*
* <p>Example: <pre> {@code
*
* public void useStreamNicely() throws IOException {
* SomeStream stream = new SomeStream("foo");
* boolean threw = true;
* try {
* // ... code which does something with the stream ...
* threw = false;
* } finally {
* // If an exception occurs, rethrow it only if threw==false:
* Closeables.close(stream, threw);
* }
* }}</pre>
*
* @param closeable the {@code Closeable} object to be closed, or null,
* in which case this method does nothing
* @param swallowIOException if true, don't propagate IO exceptions
* thrown by the {@code close} methods
* @throws IOException if {@code swallowIOException} is false and
* {@code close} throws an {@code IOException}.
*/
public static void close(@Nullable Closeable closeable,
boolean swallowIOException) throws IOException {
if (closeable == null) {
return;
}
try {
closeable.close();
} catch (IOException e) {
if (swallowIOException) {
logger.log(Level.WARNING,
"IOException thrown while closing Closeable.", e);
} else {
throw e;
}
}
}
/**
* Equivalent to calling {@code close(closeable, true)}, but with no
* IOException in the signature.
* @param closeable the {@code Closeable} object to be closed, or null, in
* which case this method does nothing
*/
public static void closeQuietly(@Nullable Closeable closeable) {
try {
close(closeable, true);
} catch (IOException e) {
logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
}
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.File;
import java.io.FilenameFilter;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.Nullable;
/**
* File name filter that only accepts files matching a regular expression. This
* class is thread-safe and immutable.
*
* @author Apple Chow
* @since 1.0
*/
@Beta
public final class PatternFilenameFilter implements FilenameFilter {
private final Pattern pattern;
/**
* Constructs a pattern file name filter object.
* @param patternStr the pattern string on which to filter file names
*
* @throws PatternSyntaxException if pattern compilation fails (runtime)
*/
public PatternFilenameFilter(String patternStr) {
this(Pattern.compile(patternStr));
}
/**
* Constructs a pattern file name filter object.
* @param pattern the pattern on which to filter file names
*/
public PatternFilenameFilter(Pattern pattern) {
this.pattern = Preconditions.checkNotNull(pattern);
}
@Override public boolean accept(@Nullable File dir, String fileName) {
return pattern.matcher(fileName).matches();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.Flushable;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Utility methods for working with {@link Flushable} objects.
*
* @author Michael Lancaster
* @since 1.0
*/
@Beta
public final class Flushables {
private static final Logger logger
= Logger.getLogger(Flushables.class.getName());
private Flushables() {}
/**
* Flush a {@link Flushable}, with control over whether an
* {@code IOException} may be thrown.
*
* <p>If {@code swallowIOException} is true, then we don't rethrow
* {@code IOException}, but merely log it.
*
* @param flushable the {@code Flushable} object to be flushed.
* @param swallowIOException if true, don't propagate IO exceptions
* thrown by the {@code flush} method
* @throws IOException if {@code swallowIOException} is false and
* {@link Flushable#flush} throws an {@code IOException}.
* @see Closeables#close
*/
public static void flush(Flushable flushable, boolean swallowIOException)
throws IOException {
try {
flushable.flush();
} catch (IOException e) {
if (swallowIOException) {
logger.log(Level.WARNING,
"IOException thrown while flushing Flushable.", e);
} else {
throw e;
}
}
}
/**
* Equivalent to calling {@code flush(flushable, true)}, but with no
* {@code IOException} in the signature.
*
* @param flushable the {@code Flushable} object to be flushed.
*/
public static void flushQuietly(Flushable flushable) {
try {
flush(flushable, true);
} catch (IOException e) {
logger.log(Level.SEVERE, "IOException should not have been thrown.", e);
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.IOException;
/**
* A factory for readable streams of bytes or characters.
*
* @author Chris Nokleberg
* @since 1.0
*/
public interface InputSupplier<T> {
/**
* Returns an object that encapsulates a readable resource.
* <p>
* Like {@link Iterable#iterator}, this method may be called repeatedly to
* get independent channels to the same underlying resource.
* <p>
* Where the channel maintains a position within the resource, moving that
* cursor within one channel should not affect the starting position of
* channels returned by other calls.
*/
T getInput() throws IOException;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* This package contains utility methods and classes for working with Java I/O,
* for example input streams, output streams, readers, writers, and files.
*
* <p>Many of the methods are based on the
* {@link com.google.common.io.InputSupplier} and
* {@link com.google.common.io.OutputSupplier} interfaces. They are used as
* factories for I/O objects that might throw {@link java.io.IOException} when
* being created. The advantage of using a factory is that the helper methods in
* this package can take care of closing the resource properly, even if an
* exception is thrown. The {@link com.google.common.io.ByteStreams},
* {@link com.google.common.io.CharStreams}, and
* {@link com.google.common.io.Files} classes all have static helper methods to
* create new factories and to work with them.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* @author Chris Nokleberg
*/
@ParametersAreNonnullByDefault
package com.google.common.io;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Provides utility methods for working with character streams.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* <p>Some of the methods in this class take arguments with a generic type of
* {@code Readable & Closeable}. A {@link java.io.Reader} implements both of
* those interfaces. Similarly for {@code Appendable & Closeable} and
* {@link java.io.Writer}.
*
* @author Chris Nokleberg
* @author Bin Zhu
* @since 1.0
*/
@Beta
public final class CharStreams {
private static final int BUF_SIZE = 0x800; // 2K chars (4K bytes)
private CharStreams() {}
/**
* Returns a factory that will supply instances of {@link StringReader} that
* read a string value.
*
* @param value the string to read
* @return the factory
*/
public static InputSupplier<StringReader> newReaderSupplier(
final String value) {
Preconditions.checkNotNull(value);
return new InputSupplier<StringReader>() {
@Override
public StringReader getInput() {
return new StringReader(value);
}
};
}
/**
* Returns a factory that will supply instances of {@link InputStreamReader},
* using the given {@link InputStream} factory and character set.
*
* @param in the factory that will be used to open input streams
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(
final InputSupplier<? extends InputStream> in, final Charset charset) {
Preconditions.checkNotNull(in);
Preconditions.checkNotNull(charset);
return new InputSupplier<InputStreamReader>() {
@Override
public InputStreamReader getInput() throws IOException {
return new InputStreamReader(in.getInput(), charset);
}
};
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter},
* using the given {@link OutputStream} factory and character set.
*
* @param out the factory that will be used to open output streams
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(
final OutputSupplier<? extends OutputStream> out, final Charset charset) {
Preconditions.checkNotNull(out);
Preconditions.checkNotNull(charset);
return new OutputSupplier<OutputStreamWriter>() {
@Override
public OutputStreamWriter getOutput() throws IOException {
return new OutputStreamWriter(out.getOutput(), charset);
}
};
}
/**
* Writes a character sequence (such as a string) to an appendable
* object from the given supplier.
*
* @param from the character sequence to write
* @param to the output supplier
* @throws IOException if an I/O error occurs
*/
public static <W extends Appendable & Closeable> void write(CharSequence from,
OutputSupplier<W> to) throws IOException {
Preconditions.checkNotNull(from);
boolean threw = true;
W out = to.getOutput();
try {
out.append(from);
threw = false;
} finally {
Closeables.close(out, threw);
}
}
/**
* Opens {@link Readable} and {@link Appendable} objects from the
* given factories, copies all characters between the two, and closes
* them.
*
* @param from the input factory
* @param to the output factory
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable,
W extends Appendable & Closeable> long copy(InputSupplier<R> from,
OutputSupplier<W> to) throws IOException {
int successfulOps = 0;
R in = from.getInput();
try {
W out = to.getOutput();
try {
long count = copy(in, out);
successfulOps++;
return count;
} finally {
Closeables.close(out, successfulOps < 1);
successfulOps++;
}
} finally {
Closeables.close(in, successfulOps < 2);
}
}
/**
* Opens a {@link Readable} object from the supplier, copies all characters
* to the {@link Appendable} object, and closes the input. Does not close
* or flush the output.
*
* @param from the input factory
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> long copy(
InputSupplier<R> from, Appendable to) throws IOException {
boolean threw = true;
R in = from.getInput();
try {
long count = copy(in, to);
threw = false;
return count;
} finally {
Closeables.close(in, threw);
}
}
/**
* Copies all characters between the {@link Readable} and {@link Appendable}
* objects. Does not close or flush either object.
*
* @param from the object to read from
* @param to the object to write to
* @return the number of characters copied
* @throws IOException if an I/O error occurs
*/
public static long copy(Readable from, Appendable to) throws IOException {
CharBuffer buf = CharBuffer.allocate(BUF_SIZE);
long total = 0;
while (from.read(buf) != -1) {
buf.flip();
to.append(buf);
total += buf.remaining();
buf.clear();
}
return total;
}
/**
* Reads all characters from a {@link Readable} object into a {@link String}.
* Does not close the {@code Readable}.
*
* @param r the object to read from
* @return a string containing all the characters
* @throws IOException if an I/O error occurs
*/
public static String toString(Readable r) throws IOException {
return toStringBuilder(r).toString();
}
/**
* Returns the characters from a {@link Readable} & {@link Closeable} object
* supplied by a factory as a {@link String}.
*
* @param supplier the factory to read from
* @return a string containing all the characters
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> String toString(
InputSupplier<R> supplier) throws IOException {
return toStringBuilder(supplier).toString();
}
/**
* Reads all characters from a {@link Readable} object into a new
* {@link StringBuilder} instance. Does not close the {@code Readable}.
*
* @param r the object to read from
* @return a {@link StringBuilder} containing all the characters
* @throws IOException if an I/O error occurs
*/
private static StringBuilder toStringBuilder(Readable r) throws IOException {
StringBuilder sb = new StringBuilder();
copy(r, sb);
return sb;
}
/**
* Returns the characters from a {@link Readable} & {@link Closeable} object
* supplied by a factory as a new {@link StringBuilder} instance.
*
* @param supplier the factory to read from
* @throws IOException if an I/O error occurs
*/
private static <R extends Readable & Closeable> StringBuilder toStringBuilder(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
StringBuilder result = toStringBuilder(r);
threw = false;
return result;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads the first line from a {@link Readable} & {@link Closeable} object
* supplied by a factory. The line does not include line-termination
* characters, but does include other leading and trailing whitespace.
*
* @param supplier the factory to read from
* @return the first line, or null if the reader is empty
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> String readFirstLine(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
String line = new LineReader(r).readLine();
threw = false;
return line;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads all of the lines from a {@link Readable} & {@link Closeable} object
* supplied by a factory. The lines do not include line-termination
* characters, but do include other leading and trailing whitespace.
*
* @param supplier the factory to read from
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> List<String> readLines(
InputSupplier<R> supplier) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
List<String> result = readLines(r);
threw = false;
return result;
} finally {
Closeables.close(r, threw);
}
}
/**
* Reads all of the lines from a {@link Readable} object. The lines do
* not include line-termination characters, but do include other
* leading and trailing whitespace.
*
* <p>Does not close the {@code Readable}. If reading files or resources you
* should use the {@link Files#readLines} and {@link Resources#readLines}
* methods.
*
* @param r the object to read from
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(Readable r) throws IOException {
List<String> result = new ArrayList<String>();
LineReader lineReader = new LineReader(r);
String line;
while ((line = lineReader.readLine()) != null) {
result.add(line);
}
return result;
}
/**
* Streams lines from a {@link Readable} and {@link Closeable} object
* supplied by a factory, stopping when our callback returns false, or we
* have read all of the lines.
*
* @param supplier the factory to read from
* @param callback the LineProcessor to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable, T> T readLines(
InputSupplier<R> supplier, LineProcessor<T> callback) throws IOException {
boolean threw = true;
R r = supplier.getInput();
try {
LineReader lineReader = new LineReader(r);
String line;
while ((line = lineReader.readLine()) != null) {
if (!callback.processLine(line)) {
break;
}
}
threw = false;
} finally {
Closeables.close(r, threw);
}
return callback.getResult();
}
/**
* Joins multiple {@link Reader} suppliers into a single supplier.
* Reader returned from the supplier will contain the concatenated data
* from the readers of the underlying suppliers.
*
* <p>Reading from the joined reader will throw a {@link NullPointerException}
* if any of the suppliers are null or return null.
*
* <p>Only one underlying reader will be open at a time. Closing the
* joined reader will close the open underlying reader.
*
* @param suppliers the suppliers to concatenate
* @return a supplier that will return a reader containing the concatenated
* data
*/
public static InputSupplier<Reader> join(
final Iterable<? extends InputSupplier<? extends Reader>> suppliers) {
return new InputSupplier<Reader>() {
@Override public Reader getInput() throws IOException {
return new MultiReader(suppliers.iterator());
}
};
}
/** Varargs form of {@link #join(Iterable)}. */
public static InputSupplier<Reader> join(
InputSupplier<? extends Reader>... suppliers) {
return join(Arrays.asList(suppliers));
}
/**
* Discards {@code n} characters of data from the reader. This method
* will block until the full amount has been skipped. Does not close the
* reader.
*
* @param reader the reader to read from
* @param n the number of characters to skip
* @throws EOFException if this stream reaches the end before skipping all
* the bytes
* @throws IOException if an I/O error occurs
*/
public static void skipFully(Reader reader, long n) throws IOException {
while (n > 0) {
long amt = reader.skip(n);
if (amt == 0) {
// force a blocking read
if (reader.read() == -1) {
throw new EOFException();
}
n--;
} else {
n -= amt;
}
}
}
/**
* Returns a Writer that sends all output to the given {@link Appendable}
* target. Closing the writer will close the target if it is {@link
* Closeable}, and flushing the writer will flush the target if it is {@link
* java.io.Flushable}.
*
* @param target the object to which output will be sent
* @return a new Writer object, unless target is a Writer, in which case the
* target is returned
*/
public static Writer asWriter(Appendable target) {
if (target instanceof Writer) {
return (Writer) target;
}
return new AppendableWriter(target);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An InputStream that limits the number of bytes which can be read.
*
* @author Charles Fry
* @since 1.0
* @deprecated Use {@link ByteStreams#limit} instead. This class is scheduled
* to be removed in Guava release 15.0.
*/
@Beta
@Deprecated
public final class LimitInputStream extends FilterInputStream {
private long left;
private long mark = -1;
/**
* Wraps another input stream, limiting the number of bytes which can be read.
*
* @param in the input stream to be wrapped
* @param limit the maximum number of bytes to be read
*/
public LimitInputStream(InputStream in, long limit) {
super(in);
Preconditions.checkNotNull(in);
Preconditions.checkArgument(limit >= 0, "limit must be non-negative");
left = limit;
}
@Override public int available() throws IOException {
return (int) Math.min(in.available(), left);
}
@Override public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = left;
// it's okay to mark even if mark isn't supported, as reset won't work
}
@Override public int read() throws IOException {
if (left == 0) {
return -1;
}
int result = in.read();
if (result != -1) {
--left;
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (left == 0) {
return -1;
}
len = (int) Math.min(len, left);
int result = in.read(b, off, len);
if (result != -1) {
left -= result;
}
return result;
}
@Override public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
left = mark;
}
@Override public long skip(long n) throws IOException {
n = Math.min(n, left);
long skipped = in.skip(n);
left -= skipped;
return skipped;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.IOException;
/**
* A callback interface to process bytes from a stream.
*
* <p>{@link #processBytes} will be called for each line that is read, and
* should return {@code false} when you want to stop processing.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public interface ByteProcessor<T> {
/**
* This method will be called for each chunk of bytes in an
* input stream. The implementation should process the bytes
* from {@code buf[off]} through {@code buf[off + len - 1]}
* (inclusive).
*
* @param buf the byte array containing the data to process
* @param off the initial offset into the array
* @param len the length of data to be processed
* @return true to continue processing, false to stop
*/
boolean processBytes(byte[] buf, int off, int len) throws IOException;
/** Return the result of processing all the bytes. */
T getResult();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An OutputStream that counts the number of bytes written.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class CountingOutputStream extends FilterOutputStream {
private long count;
/**
* Wraps another output stream, counting the number of bytes written.
*
* @param out the output stream to be wrapped
*/
public CountingOutputStream(OutputStream out) {
super(out);
}
/** Returns the number of bytes written. */
public long getCount() {
return count;
}
@Override public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
count += len;
}
@Override public void write(int b) throws IOException {
out.write(b);
count++;
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.DataInput;
import java.io.IOException;
/**
* An extension of {@code DataInput} for reading from in-memory byte arrays; its
* methods offer identical functionality but do not throw {@link IOException}.
*
* <p><b>Warning:<b> The caller is responsible for not attempting to read past
* the end of the array. If any method encounters the end of the array
* prematurely, it throws {@link IllegalStateException} to signify <i>programmer
* error</i>. This behavior is a technical violation of the supertype's
* contract, which specifies a checked exception.
*
* @author Kevin Bourrillion
* @since 1.0
*/
public interface ByteArrayDataInput extends DataInput {
@Override void readFully(byte b[]);
@Override void readFully(byte b[], int off, int len);
@Override int skipBytes(int n);
@Override boolean readBoolean();
@Override byte readByte();
@Override int readUnsignedByte();
@Override short readShort();
@Override int readUnsignedShort();
@Override char readChar();
@Override int readInt();
@Override long readLong();
@Override float readFloat();
@Override double readDouble();
@Override String readLine();
@Override String readUTF();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An {@link InputStream} that counts the number of bytes read.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class CountingInputStream extends FilterInputStream {
private long count;
private long mark = -1;
/**
* Wraps another input stream, counting the number of bytes read.
*
* @param in the input stream to be wrapped
*/
public CountingInputStream(InputStream in) {
super(in);
}
/** Returns the number of bytes read. */
public long getCount() {
return count;
}
@Override public int read() throws IOException {
int result = in.read();
if (result != -1) {
count++;
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int result = in.read(b, off, len);
if (result != -1) {
count += result;
}
return result;
}
@Override public long skip(long n) throws IOException {
long result = in.skip(n);
count += result;
return result;
}
@Override public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = count;
// it's okay to mark even if mark isn't supported, as reset won't work
}
@Override public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
count = mark;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* An implementation of {@link DataInput} that uses little-endian byte ordering
* for reading {@code short}, {@code int}, {@code float}, {@code double}, and
* {@code long} values.
* <p>
* <b>Note:</b> This class intentionally violates the specification of its
* supertype {@code DataInput}, which explicitly requires big-endian byte order.
*
* @author Chris Nokleberg
* @author Keith Bottner
* @since 8.0
*/
@Beta
public final class LittleEndianDataInputStream extends FilterInputStream
implements DataInput {
/**
* Creates a {@code LittleEndianDataInputStream} that wraps the given stream.
*
* @param in the stream to delegate to
*/
public LittleEndianDataInputStream(InputStream in) {
super(Preconditions.checkNotNull(in));
}
/**
* This method will throw an {@link UnsupportedOperationException}.
*/
@Override
public String readLine() {
throw new UnsupportedOperationException("readLine is not supported");
}
@Override
public void readFully(byte[] b) throws IOException {
ByteStreams.readFully(this, b);
}
@Override
public void readFully(byte[] b, int off, int len) throws IOException {
ByteStreams.readFully(this, b, off, len);
}
@Override
public int skipBytes(int n) throws IOException {
return (int) in.skip(n);
}
@Override
public int readUnsignedByte() throws IOException {
int b1 = in.read();
if (0 > b1) {
throw new EOFException();
}
return b1;
}
/**
* Reads an unsigned {@code short} as specified by
* {@link DataInputStream#readUnsignedShort()}, except using little-endian
* byte order.
*
* @return the next two bytes of the input stream, interpreted as an
* unsigned 16-bit integer in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public int readUnsignedShort() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
return Ints.fromBytes((byte) 0, (byte) 0, b2, b1);
}
/**
* Reads an integer as specified by {@link DataInputStream#readInt()}, except
* using little-endian byte order.
*
* @return the next four bytes of the input stream, interpreted as an
* {@code int} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public int readInt() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
byte b3 = readAndCheckByte();
byte b4 = readAndCheckByte();
return Ints.fromBytes( b4, b3, b2, b1);
}
/**
* Reads a {@code long} as specified by {@link DataInputStream#readLong()},
* except using little-endian byte order.
*
* @return the next eight bytes of the input stream, interpreted as a
* {@code long} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public long readLong() throws IOException {
byte b1 = readAndCheckByte();
byte b2 = readAndCheckByte();
byte b3 = readAndCheckByte();
byte b4 = readAndCheckByte();
byte b5 = readAndCheckByte();
byte b6 = readAndCheckByte();
byte b7 = readAndCheckByte();
byte b8 = readAndCheckByte();
return Longs.fromBytes(b8, b7, b6, b5, b4, b3, b2, b1);
}
/**
* Reads a {@code float} as specified by {@link DataInputStream#readFloat()},
* except using little-endian byte order.
*
* @return the next four bytes of the input stream, interpreted as a
* {@code float} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public float readFloat() throws IOException {
return Float.intBitsToFloat(readInt());
}
/**
* Reads a {@code double} as specified by
* {@link DataInputStream#readDouble()}, except using little-endian byte
* order.
*
* @return the next eight bytes of the input stream, interpreted as a
* {@code double} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public double readDouble() throws IOException {
return Double.longBitsToDouble(readLong());
}
@Override
public String readUTF() throws IOException {
return new DataInputStream(in).readUTF();
}
/**
* Reads a {@code short} as specified by {@link DataInputStream#readShort()},
* except using little-endian byte order.
*
* @return the next two bytes of the input stream, interpreted as a
* {@code short} in little-endian byte order.
* @throws IOException if an I/O error occurs.
*/
@Override
public short readShort() throws IOException {
return (short) readUnsignedShort();
}
/**
* Reads a char as specified by {@link DataInputStream#readChar()}, except
* using little-endian byte order.
*
* @return the next two bytes of the input stream, interpreted as a
* {@code char} in little-endian byte order
* @throws IOException if an I/O error occurs
*/
@Override
public char readChar() throws IOException {
return (char) readUnsignedShort();
}
@Override
public byte readByte() throws IOException {
return (byte) readUnsignedByte();
}
@Override
public boolean readBoolean() throws IOException {
return readUnsignedByte() != 0;
}
/**
* Reads a byte from the input stream checking that the end of file (EOF)
* has not been encountered.
*
* @return byte read from input
* @throws IOException if an error is encountered while reading
* @throws EOFException if the end of file (EOF) is encountered.
*/
private byte readAndCheckByte() throws IOException, EOFException {
int b1 = in.read();
if (-1 == b1) {
throw new EOFException();
}
return (byte) b1;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.IOException;
/**
* A factory for writable streams of bytes or characters.
*
* @author Chris Nokleberg
* @since 1.0
*/
public interface OutputSupplier<T> {
/**
* Returns an object that encapsulates a writable resource.
* <p>
* Like {@link Iterable#iterator}, this method may be called repeatedly to
* get independent channels to the same underlying resource.
* <p>
* Where the channel maintains a position within the resource, moving that
* cursor within one channel should not affect the starting position of
* channels returned by other calls.
*/
T getOutput() throws IOException;
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import java.io.Writer;
/**
* Writer that places all output on an {@link Appendable} target. If the target
* is {@link Flushable} or {@link Closeable}, flush()es and close()s will also
* be delegated to the target.
*
* @author Alan Green
* @author Sebastian Kanthak
* @since 1.0
*/
class AppendableWriter extends Writer {
private final Appendable target;
private boolean closed;
/**
* Creates a new writer that appends everything it writes to {@code target}.
*
* @param target target to which to append output
*/
AppendableWriter(Appendable target) {
this.target = target;
}
/*
* Abstract methods from Writer
*/
@Override public void write(char cbuf[], int off, int len)
throws IOException {
checkNotClosed();
// It turns out that creating a new String is usually as fast, or faster
// than wrapping cbuf in a light-weight CharSequence.
target.append(new String(cbuf, off, len));
}
@Override public void flush() throws IOException {
checkNotClosed();
if (target instanceof Flushable) {
((Flushable) target).flush();
}
}
@Override public void close() throws IOException {
this.closed = true;
if (target instanceof Closeable) {
((Closeable) target).close();
}
}
/*
* Override a few functions for performance reasons to avoid creating
* unnecessary strings.
*/
@Override public void write(int c) throws IOException {
checkNotClosed();
target.append((char) c);
}
@Override public void write(String str) throws IOException {
checkNotClosed();
target.append(str);
}
@Override public void write(String str, int off, int len) throws IOException {
checkNotClosed();
// tricky: append takes start, end pair...
target.append(str, off, off + len);
}
@Override public Writer append(char c) throws IOException {
checkNotClosed();
target.append(c);
return this;
}
@Override public Writer append(CharSequence charSeq) throws IOException {
checkNotClosed();
target.append(charSeq);
return this;
}
@Override public Writer append(CharSequence charSeq, int start, int end)
throws IOException {
checkNotClosed();
target.append(charSeq, start, end);
return this;
}
private void checkNotClosed() throws IOException {
if (closed) {
throw new IOException("Cannot write to a closed writer.");
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.DataOutput;
import java.io.IOException;
/**
* An extension of {@code DataOutput} for writing to in-memory byte arrays; its
* methods offer identical functionality but do not throw {@link IOException}.
*
* @author Jayaprabhakar Kadarkarai
* @since 1.0
*/
public interface ByteArrayDataOutput extends DataOutput {
@Override void write(int b);
@Override void write(byte b[]);
@Override void write(byte b[], int off, int len);
@Override void writeBoolean(boolean v);
@Override void writeByte(int v);
@Override void writeShort(int v);
@Override void writeChar(int v);
@Override void writeInt(int v);
@Override void writeLong(long v);
@Override void writeFloat(float v);
@Override void writeDouble(double v);
@Override void writeChars(String s);
@Override void writeUTF(String s);
/**
* @deprecated This method is dangerous as it discards the high byte of
* every character. For UTF-8, use {@code write(s.getBytes(Charsets.UTF_8))}.
*/
@Deprecated @Override void writeBytes(String s);
/**
* Returns the contents that have been written to this instance,
* as a byte array.
*/
byte[] toByteArray();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.hash.Funnels;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hasher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
import java.util.zip.Checksum;
/**
* Provides utility methods for working with byte arrays and I/O streams.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class ByteStreams {
private static final int BUF_SIZE = 0x1000; // 4K
private ByteStreams() {}
/**
* Returns a factory that will supply instances of
* {@link ByteArrayInputStream} that read from the given byte array.
*
* @param b the input buffer
* @return the factory
*/
public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier(
byte[] b) {
return newInputStreamSupplier(b, 0, b.length);
}
/**
* Returns a factory that will supply instances of
* {@link ByteArrayInputStream} that read from the given byte array.
*
* @param b the input buffer
* @param off the offset in the buffer of the first byte to read
* @param len the maximum number of bytes to read from the buffer
* @return the factory
*/
public static InputSupplier<ByteArrayInputStream> newInputStreamSupplier(
final byte[] b, final int off, final int len) {
return new InputSupplier<ByteArrayInputStream>() {
@Override
public ByteArrayInputStream getInput() {
return new ByteArrayInputStream(b, off, len);
}
};
}
/**
* Writes a byte array to an output stream from the given supplier.
*
* @param from the bytes to write
* @param to the output supplier
* @throws IOException if an I/O error occurs
*/
public static void write(byte[] from,
OutputSupplier<? extends OutputStream> to) throws IOException {
Preconditions.checkNotNull(from);
boolean threw = true;
OutputStream out = to.getOutput();
try {
out.write(from);
threw = false;
} finally {
Closeables.close(out, threw);
}
}
/**
* Opens input and output streams from the given suppliers, copies all
* bytes from the input to the output, and closes the streams.
*
* @param from the input factory
* @param to the output factory
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputSupplier<? extends InputStream> from,
OutputSupplier<? extends OutputStream> to) throws IOException {
int successfulOps = 0;
InputStream in = from.getInput();
try {
OutputStream out = to.getOutput();
try {
long count = copy(in, out);
successfulOps++;
return count;
} finally {
Closeables.close(out, successfulOps < 1);
successfulOps++;
}
} finally {
Closeables.close(in, successfulOps < 2);
}
}
/**
* Opens an input stream from the supplier, copies all bytes from the
* input to the output, and closes the input stream. Does not close
* or flush the output stream.
*
* @param from the input factory
* @param to the output stream to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputSupplier<? extends InputStream> from,
OutputStream to) throws IOException {
boolean threw = true;
InputStream in = from.getInput();
try {
long count = copy(in, to);
threw = false;
return count;
} finally {
Closeables.close(in, threw);
}
}
/**
* Opens an output stream from the supplier, copies all bytes from the input
* to the output, and closes the output stream. Does not close or flush the
* input stream.
*
* @param from the input stream to read from
* @param to the output factory
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
* @since 10.0
*/
public static long copy(InputStream from,
OutputSupplier<? extends OutputStream> to) throws IOException {
boolean threw = true;
OutputStream out = to.getOutput();
try {
long count = copy(from, out);
threw = false;
return count;
} finally {
Closeables.close(out, threw);
}
}
/**
* Copies all bytes from the input stream to the output stream.
* Does not close or flush either stream.
*
* @param from the input stream to read from
* @param to the output stream to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(InputStream from, OutputStream to)
throws IOException {
byte[] buf = new byte[BUF_SIZE];
long total = 0;
while (true) {
int r = from.read(buf);
if (r == -1) {
break;
}
to.write(buf, 0, r);
total += r;
}
return total;
}
/**
* Copies all bytes from the readable channel to the writable channel.
* Does not close or flush either channel.
*
* @param from the readable channel to read from
* @param to the writable channel to write to
* @return the number of bytes copied
* @throws IOException if an I/O error occurs
*/
public static long copy(ReadableByteChannel from,
WritableByteChannel to) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE);
long total = 0;
while (from.read(buf) != -1) {
buf.flip();
while (buf.hasRemaining()) {
total += to.write(buf);
}
buf.clear();
}
return total;
}
/**
* Reads all bytes from an input stream into a byte array.
* Does not close the stream.
*
* @param in the input stream to read from
* @return a byte array containing all the bytes from the stream
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in, out);
return out.toByteArray();
}
/**
* Returns the data from a {@link InputStream} factory as a byte array.
*
* @param supplier the factory
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(
InputSupplier<? extends InputStream> supplier) throws IOException {
boolean threw = true;
InputStream in = supplier.getInput();
try {
byte[] result = toByteArray(in);
threw = false;
return result;
} finally {
Closeables.close(in, threw);
}
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code
* bytes} array from the beginning.
*/
public static ByteArrayDataInput newDataInput(byte[] bytes) {
return new ByteArrayDataInputStream(bytes);
}
/**
* Returns a new {@link ByteArrayDataInput} instance to read from the {@code
* bytes} array, starting at the given position.
*
* @throws IndexOutOfBoundsException if {@code start} is negative or greater
* than the length of the array
*/
public static ByteArrayDataInput newDataInput(byte[] bytes, int start) {
Preconditions.checkPositionIndex(start, bytes.length);
return new ByteArrayDataInputStream(bytes, start);
}
private static class ByteArrayDataInputStream implements ByteArrayDataInput {
final DataInput input;
ByteArrayDataInputStream(byte[] bytes) {
this.input = new DataInputStream(new ByteArrayInputStream(bytes));
}
ByteArrayDataInputStream(byte[] bytes, int start) {
this.input = new DataInputStream(
new ByteArrayInputStream(bytes, start, bytes.length - start));
}
@Override public void readFully(byte b[]) {
try {
input.readFully(b);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public void readFully(byte b[], int off, int len) {
try {
input.readFully(b, off, len);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int skipBytes(int n) {
try {
return input.skipBytes(n);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public boolean readBoolean() {
try {
return input.readBoolean();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public byte readByte() {
try {
return input.readByte();
} catch (EOFException e) {
throw new IllegalStateException(e);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public int readUnsignedByte() {
try {
return input.readUnsignedByte();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public short readShort() {
try {
return input.readShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int readUnsignedShort() {
try {
return input.readUnsignedShort();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public char readChar() {
try {
return input.readChar();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public int readInt() {
try {
return input.readInt();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public long readLong() {
try {
return input.readLong();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public float readFloat() {
try {
return input.readFloat();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public double readDouble() {
try {
return input.readDouble();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public String readLine() {
try {
return input.readLine();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
@Override public String readUTF() {
try {
return input.readUTF();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
}
/**
* Returns a new {@link ByteArrayDataOutput} instance with a default size.
*/
public static ByteArrayDataOutput newDataOutput() {
return new ByteArrayDataOutputStream();
}
/**
* Returns a new {@link ByteArrayDataOutput} instance sized to hold
* {@code size} bytes before resizing.
*
* @throws IllegalArgumentException if {@code size} is negative
*/
public static ByteArrayDataOutput newDataOutput(int size) {
Preconditions.checkArgument(size >= 0, "Invalid size: %s", size);
return new ByteArrayDataOutputStream(size);
}
@SuppressWarnings("deprecation") // for writeBytes
private static class ByteArrayDataOutputStream
implements ByteArrayDataOutput {
final DataOutput output;
final ByteArrayOutputStream byteArrayOutputSteam;
ByteArrayDataOutputStream() {
this(new ByteArrayOutputStream());
}
ByteArrayDataOutputStream(int size) {
this(new ByteArrayOutputStream(size));
}
ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputSteam) {
this.byteArrayOutputSteam = byteArrayOutputSteam;
output = new DataOutputStream(byteArrayOutputSteam);
}
@Override public void write(int b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void write(byte[] b) {
try {
output.write(b);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void write(byte[] b, int off, int len) {
try {
output.write(b, off, len);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeBoolean(boolean v) {
try {
output.writeBoolean(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeByte(int v) {
try {
output.writeByte(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeBytes(String s) {
try {
output.writeBytes(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeChar(int v) {
try {
output.writeChar(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeChars(String s) {
try {
output.writeChars(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeDouble(double v) {
try {
output.writeDouble(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeFloat(float v) {
try {
output.writeFloat(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeInt(int v) {
try {
output.writeInt(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeLong(long v) {
try {
output.writeLong(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeShort(int v) {
try {
output.writeShort(v);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public void writeUTF(String s) {
try {
output.writeUTF(s);
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
}
@Override public byte[] toByteArray() {
return byteArrayOutputSteam.toByteArray();
}
}
private static final OutputStream NULL_OUTPUT_STREAM =
new OutputStream() {
/** Discards the specified byte. */
@Override public void write(int b) {
}
/** Discards the specified byte array. */
@Override public void write(byte[] b) {
}
/** Discards the specified byte array. */
@Override public void write(byte[] b, int off, int len) {
}
};
/**
* Returns a {@link OutputStream} that simply discards written bytes.
*
* @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream)
*/
public static OutputStream nullOutputStream() {
return NULL_OUTPUT_STREAM;
}
/**
* Wraps a {@link InputStream}, limiting the number of bytes which can be
* read.
*
* @param in the input stream to be wrapped
* @param limit the maximum number of bytes to be read
* @return a length-limited {@link InputStream}
* @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream)
*/
public static InputStream limit(InputStream in, long limit) {
return new LimitedInputStream(in, limit);
}
private static final class LimitedInputStream extends FilterInputStream {
private long left;
private long mark = -1;
LimitedInputStream(InputStream in, long limit) {
super(in);
Preconditions.checkNotNull(in);
Preconditions.checkArgument(limit >= 0, "limit must be non-negative");
left = limit;
}
@Override public int available() throws IOException {
return (int) Math.min(in.available(), left);
}
// it's okay to mark even if mark isn't supported, as reset won't work
@Override public synchronized void mark(int readlimit) {
in.mark(readlimit);
mark = left;
}
@Override public int read() throws IOException {
if (left == 0) {
return -1;
}
int result = in.read();
if (result != -1) {
--left;
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (left == 0) {
return -1;
}
len = (int) Math.min(len, left);
int result = in.read(b, off, len);
if (result != -1) {
left -= result;
}
return result;
}
@Override public synchronized void reset() throws IOException {
if (!in.markSupported()) {
throw new IOException("Mark not supported");
}
if (mark == -1) {
throw new IOException("Mark not set");
}
in.reset();
left = mark;
}
@Override public long skip(long n) throws IOException {
n = Math.min(n, left);
long skipped = in.skip(n);
left -= skipped;
return skipped;
}
}
// TODO(chrisn): Not all streams support skipping.
/** Returns the length of a supplied input stream, in bytes. */
public static long length(
InputSupplier<? extends InputStream> supplier) throws IOException {
long count = 0;
boolean threw = true;
InputStream in = supplier.getInput();
try {
while (true) {
// We skip only Integer.MAX_VALUE due to JDK overflow bugs.
long amt = in.skip(Integer.MAX_VALUE);
if (amt == 0) {
if (in.read() == -1) {
threw = false;
return count;
}
count++;
} else {
count += amt;
}
}
} finally {
Closeables.close(in, threw);
}
}
/**
* Returns true if the supplied input streams contain the same bytes.
*
* @throws IOException if an I/O error occurs
*/
public static boolean equal(InputSupplier<? extends InputStream> supplier1,
InputSupplier<? extends InputStream> supplier2) throws IOException {
byte[] buf1 = new byte[BUF_SIZE];
byte[] buf2 = new byte[BUF_SIZE];
boolean threw = true;
InputStream in1 = supplier1.getInput();
try {
InputStream in2 = supplier2.getInput();
try {
while (true) {
int read1 = read(in1, buf1, 0, BUF_SIZE);
int read2 = read(in2, buf2, 0, BUF_SIZE);
if (read1 != read2 || !Arrays.equals(buf1, buf2)) {
threw = false;
return false;
} else if (read1 != BUF_SIZE) {
threw = false;
return true;
}
}
} finally {
Closeables.close(in2, threw);
}
} finally {
Closeables.close(in1, threw);
}
}
/**
* Attempts to read enough bytes from the stream to fill the given byte array,
* with the same behavior as {@link DataInput#readFully(byte[])}.
* Does not close the stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @throws EOFException if this stream reaches the end before reading all
* the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(InputStream in, byte[] b) throws IOException {
readFully(in, b, 0, b.length);
}
/**
* Attempts to read {@code len} bytes from the stream into the given array
* starting at {@code off}, with the same behavior as
* {@link DataInput#readFully(byte[], int, int)}. Does not close the
* stream.
*
* @param in the input stream to read from.
* @param b the buffer into which the data is read.
* @param off an int specifying the offset into the data.
* @param len an int specifying the number of bytes to read.
* @throws EOFException if this stream reaches the end before reading all
* the bytes.
* @throws IOException if an I/O error occurs.
*/
public static void readFully(
InputStream in, byte[] b, int off, int len) throws IOException {
if (read(in, b, off, len) != len) {
throw new EOFException();
}
}
/**
* Discards {@code n} bytes of data from the input stream. This method
* will block until the full amount has been skipped. Does not close the
* stream.
*
* @param in the input stream to read from
* @param n the number of bytes to skip
* @throws EOFException if this stream reaches the end before skipping all
* the bytes
* @throws IOException if an I/O error occurs, or the stream does not
* support skipping
*/
public static void skipFully(InputStream in, long n) throws IOException {
while (n > 0) {
long amt = in.skip(n);
if (amt == 0) {
// Force a blocking read to avoid infinite loop
if (in.read() == -1) {
throw new EOFException();
}
n--;
} else {
n -= amt;
}
}
}
/**
* Process the bytes of a supplied stream
*
* @param supplier the input stream factory
* @param processor the object to which to pass the bytes of the stream
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
*/
public static <T> T readBytes(
InputSupplier<? extends InputStream> supplier,
ByteProcessor<T> processor) throws IOException {
byte[] buf = new byte[BUF_SIZE];
boolean threw = true;
InputStream in = supplier.getInput();
try {
int amt;
do {
amt = in.read(buf);
if (amt == -1) {
threw = false;
break;
}
} while (processor.processBytes(buf, 0, amt));
return processor.getResult();
} finally {
Closeables.close(in, threw);
}
}
/**
* Computes and returns the checksum value for a supplied input stream.
* The checksum object is reset when this method returns successfully.
*
* @param supplier the input stream factory
* @param checksum the checksum object
* @return the result of {@link Checksum#getValue} after updating the
* checksum object with all of the bytes in the stream
* @throws IOException if an I/O error occurs
*/
public static long getChecksum(
InputSupplier<? extends InputStream> supplier, final Checksum checksum)
throws IOException {
return readBytes(supplier, new ByteProcessor<Long>() {
@Override
public boolean processBytes(byte[] buf, int off, int len) {
checksum.update(buf, off, len);
return true;
}
@Override
public Long getResult() {
long result = checksum.getValue();
checksum.reset();
return result;
}
});
}
/**
* Computes the hash code of the data supplied by {@code supplier} using {@code
* hashFunction}.
*
* @param supplier the input stream factory
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the input stream
* @throws IOException if an I/O error occurs
* @since 12.0
*/
public static HashCode hash(
InputSupplier<? extends InputStream> supplier, HashFunction hashFunction)
throws IOException {
Hasher hasher = hashFunction.newHasher();
copy(supplier, Funnels.asOutputStream(hasher));
return hasher.hash();
}
/**
* Reads some bytes from an input stream and stores them into the buffer array
* {@code b}. This method blocks until {@code len} bytes of input data have
* been read into the array, or end of file is detected. The number of bytes
* read is returned, possibly zero. Does not close the stream.
*
* <p>A caller can detect EOF if the number of bytes read is less than
* {@code len}. All subsequent calls on the same stream will return zero.
*
* <p>If {@code b} is null, a {@code NullPointerException} is thrown. If
* {@code off} is negative, or {@code len} is negative, or {@code off+len} is
* greater than the length of the array {@code b}, then an
* {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then
* no bytes are read. Otherwise, the first byte read is stored into element
* {@code b[off]}, the next one into {@code b[off+1]}, and so on. The number
* of bytes read is, at most, equal to {@code len}.
*
* @param in the input stream to read from
* @param b the buffer into which the data is read
* @param off an int specifying the offset into the data
* @param len an int specifying the number of bytes to read
* @return the number of bytes read
* @throws IOException if an I/O error occurs
*/
public static int read(InputStream in, byte[] b, int off, int len)
throws IOException {
if (len < 0) {
throw new IndexOutOfBoundsException("len is negative");
}
int total = 0;
while (total < len) {
int result = in.read(b, off + total, len - total);
if (result == -1) {
break;
}
total += result;
}
return total;
}
/**
* Returns an {@link InputSupplier} that returns input streams from the
* an underlying supplier, where each stream starts at the given
* offset and is limited to the specified number of bytes.
*
* @param supplier the supplier from which to get the raw streams
* @param offset the offset in bytes into the underlying stream where
* the returned streams will start
* @param length the maximum length of the returned streams
* @throws IllegalArgumentException if offset or length are negative
*/
public static InputSupplier<InputStream> slice(
final InputSupplier<? extends InputStream> supplier,
final long offset,
final long length) {
Preconditions.checkNotNull(supplier);
Preconditions.checkArgument(offset >= 0, "offset is negative");
Preconditions.checkArgument(length >= 0, "length is negative");
return new InputSupplier<InputStream>() {
@Override public InputStream getInput() throws IOException {
InputStream in = supplier.getInput();
if (offset > 0) {
try {
skipFully(in, offset);
} catch (IOException e) {
Closeables.closeQuietly(in);
throw e;
}
}
return limit(in, length);
}
};
}
/**
* Joins multiple {@link InputStream} suppliers into a single supplier.
* Streams returned from the supplier will contain the concatenated data from
* the streams of the underlying suppliers.
*
* <p>Only one underlying input stream will be open at a time. Closing the
* joined stream will close the open underlying stream.
*
* <p>Reading from the joined stream will throw a {@link NullPointerException}
* if any of the suppliers are null or return null.
*
* @param suppliers the suppliers to concatenate
* @return a supplier that will return a stream containing the concatenated
* stream data
*/
public static InputSupplier<InputStream> join(final
Iterable<? extends InputSupplier<? extends InputStream>> suppliers) {
return new InputSupplier<InputStream>() {
@Override public InputStream getInput() throws IOException {
return new MultiInputStream(suppliers.iterator());
}
};
}
/** Varargs form of {@link #join(Iterable)}. */
public static InputSupplier<InputStream> join(
InputSupplier<? extends InputStream>... suppliers) {
return join(Arrays.asList(suppliers));
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.IOException;
/**
* A callback to be used with the streaming {@code readLines} methods.
*
* <p>{@link #processLine} will be called for each line that is read, and
* should return {@code false} when you want to stop processing.
*
* @author Miles Barr
* @since 1.0
*/
@Beta
public interface LineProcessor<T> {
/**
* This method will be called once for each line.
*
* @param line the line read from the input, without delimiter
* @return true to continue processing, false to stop
*/
boolean processLine(String line) throws IOException;
/** Return the result of processing all the lines. */
T getResult();
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Longs;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* An implementation of {@link DataOutput} that uses little-endian byte ordering
* for writing {@code char}, {@code short}, {@code int}, {@code float}, {@code
* double}, and {@code long} values.
* <p>
* <b>Note:</b> This class intentionally violates the specification of its
* supertype {@code DataOutput}, which explicitly requires big-endian byte
* order.
*
* @author Chris Nokleberg
* @author Keith Bottner
* @since 8.0
*/
@Beta
public class LittleEndianDataOutputStream extends FilterOutputStream
implements DataOutput {
/**
* Creates a {@code LittleEndianDataOutputStream} that wraps the given stream.
*
* @param out the stream to delegate to
*/
public LittleEndianDataOutputStream(OutputStream out) {
super(new DataOutputStream(Preconditions.checkNotNull(out)));
}
@Override public void write(byte[] b, int off, int len) throws IOException {
// Override slow FilterOutputStream impl
out.write(b, off, len);
}
@Override public void writeBoolean(boolean v) throws IOException {
((DataOutputStream) out).writeBoolean(v);
}
@Override public void writeByte(int v) throws IOException {
((DataOutputStream) out).writeByte(v);
}
/**
* @deprecated The semantics of {@code writeBytes(String s)} are considered
* dangerous. Please use {@link #writeUTF(String s)},
* {@link #writeChars(String s)} or another write method instead.
*/
@Deprecated
@Override public void writeBytes(String s) throws IOException {
((DataOutputStream) out).writeBytes(s);
}
/**
* Writes a char as specified by {@link DataOutputStream#writeChar(int)},
* except using little-endian byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeChar(int v) throws IOException {
writeShort(v);
}
/**
* Writes a {@code String} as specified by
* {@link DataOutputStream#writeChars(String)}, except each character is
* written using little-endian byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeChars(String s) throws IOException {
for (int i = 0; i < s.length(); i++) {
writeChar(s.charAt(i));
}
}
/**
* Writes a {@code double} as specified by
* {@link DataOutputStream#writeDouble(double)}, except using little-endian
* byte order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
/**
* Writes a {@code float} as specified by
* {@link DataOutputStream#writeFloat(float)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
/**
* Writes an {@code int} as specified by
* {@link DataOutputStream#writeInt(int)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeInt(int v) throws IOException {
out.write(0xFF & v);
out.write(0xFF & (v >> 8));
out.write(0xFF & (v >> 16));
out.write(0xFF & (v >> 24));
}
/**
* Writes a {@code long} as specified by
* {@link DataOutputStream#writeLong(long)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeLong(long v) throws IOException {
byte[] bytes = Longs.toByteArray(Long.reverseBytes(v));
write(bytes, 0, bytes.length);
}
/**
* Writes a {@code short} as specified by
* {@link DataOutputStream#writeShort(int)}, except using little-endian byte
* order.
*
* @throws IOException if an I/O error occurs
*/
@Override public void writeShort(int v) throws IOException {
out.write(0xFF & v);
out.write(0xFF & (v >> 8));
}
@Override public void writeUTF(String str) throws IOException {
((DataOutputStream) out).writeUTF(str);
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Charsets;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
/**
* Provides utility methods for working with resources in the classpath.
* Note that even though these methods use {@link URL} parameters, they
* are usually not appropriate for HTTP or other non-classpath resources.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* @author Chris Nokleberg
* @author Ben Yu
* @since 1.0
*/
@Beta
public final class Resources {
private Resources() {}
/**
* Returns a factory that will supply instances of {@link InputStream} that
* read from the given URL.
*
* @param url the URL to read from
* @return the factory
*/
public static InputSupplier<InputStream> newInputStreamSupplier(
final URL url) {
checkNotNull(url);
return new InputSupplier<InputStream>() {
@Override
public InputStream getInput() throws IOException {
return url.openStream();
}
};
}
/**
* Returns a factory that will supply instances of
* {@link InputStreamReader} that read a URL using the given character set.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(
URL url, Charset charset) {
return CharStreams.newReaderSupplier(newInputStreamSupplier(url), charset);
}
/**
* Reads all bytes from a URL into a byte array.
*
* @param url the URL to read from
* @return a byte array containing all the bytes from the URL
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(URL url) throws IOException {
return ByteStreams.toByteArray(newInputStreamSupplier(url));
}
/**
* Reads all characters from a URL into a {@link String}, using the given
* character set.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return a string containing all the characters from the URL
* @throws IOException if an I/O error occurs.
*/
public static String toString(URL url, Charset charset) throws IOException {
return CharStreams.toString(newReaderSupplier(url, charset));
}
/**
* Streams lines from a URL, stopping when our callback returns false, or we
* have read all of the lines.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @param callback the LineProcessor to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <T> T readLines(URL url, Charset charset,
LineProcessor<T> callback) throws IOException {
return CharStreams.readLines(newReaderSupplier(url, charset), callback);
}
/**
* Reads all of the lines from a URL. The lines do not include
* line-termination characters, but do include other leading and trailing
* whitespace.
*
* @param url the URL to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(URL url, Charset charset)
throws IOException {
return CharStreams.readLines(newReaderSupplier(url, charset));
}
/**
* Copies all bytes from a URL to an output stream.
*
* @param from the URL to read from
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(URL from, OutputStream to) throws IOException {
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Returns a {@code URL} pointing to {@code resourceName} if the resource is
* found in the class path. {@code Resources.class.getClassLoader()} is used
* to locate the resource.
*
* @throws IllegalArgumentException if resource is not found
*/
public static URL getResource(String resourceName) {
URL url = Resources.class.getClassLoader().getResource(resourceName);
checkArgument(url != null, "resource %s not found.", resourceName);
return url;
}
/**
* Returns a {@code URL} pointing to {@code resourceName} that is relative to
* {@code contextClass}, if the resource is found in the class path.
*
* @throws IllegalArgumentException if resource is not found
*/
public static URL getResource(Class<?> contextClass, String resourceName) {
URL url = contextClass.getResource(resourceName);
checkArgument(url != null, "resource %s relative to %s not found.",
resourceName, contextClass.getName());
return url;
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* An {@link InputStream} that concatenates multiple substreams. At most
* one stream will be open at a time.
*
* @author Chris Nokleberg
* @since 1.0
*/
final class MultiInputStream extends InputStream {
private Iterator<? extends InputSupplier<? extends InputStream>> it;
private InputStream in;
/**
* Creates a new instance.
*
* @param it an iterator of I/O suppliers that will provide each substream
*/
public MultiInputStream(
Iterator<? extends InputSupplier<? extends InputStream>> it)
throws IOException {
this.it = it;
advance();
}
@Override public void close() throws IOException {
if (in != null) {
try {
in.close();
} finally {
in = null;
}
}
}
/**
* Closes the current input stream and opens the next one, if any.
*/
private void advance() throws IOException {
close();
if (it.hasNext()) {
in = it.next().getInput();
}
}
@Override public int available() throws IOException {
if (in == null) {
return 0;
}
return in.available();
}
@Override public boolean markSupported() {
return false;
}
@Override public int read() throws IOException {
if (in == null) {
return -1;
}
int result = in.read();
if (result == -1) {
advance();
return read();
}
return result;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (in == null) {
return -1;
}
int result = in.read(b, off, len);
if (result == -1) {
advance();
return read(b, off, len);
}
return result;
}
@Override public long skip(long n) throws IOException {
if (in == null || n <= 0) {
return 0;
}
long result = in.skip(n);
if (result != 0) {
return result;
}
if (read() == -1) {
return 0;
}
return 1 + in.skip(n - 1);
}
}
| Java |
/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
/**
* A {@link Reader} that concatenates multiple readers.
*
* @author Bin Zhu
* @since 1.0
*/
class MultiReader extends Reader {
private final Iterator<? extends InputSupplier<? extends Reader>> it;
private Reader current;
MultiReader(Iterator<? extends InputSupplier<? extends Reader>> readers)
throws IOException {
this.it = readers;
advance();
}
/**
* Closes the current reader and opens the next one, if any.
*/
private void advance() throws IOException {
close();
if (it.hasNext()) {
current = it.next().getInput();
}
}
@Override public int read(char cbuf[], int off, int len) throws IOException {
if (current == null) {
return -1;
}
int result = current.read(cbuf, off, len);
if (result == -1) {
advance();
return read(cbuf, off, len);
}
return result;
}
@Override public long skip(long n) throws IOException {
Preconditions.checkArgument(n >= 0, "n is negative");
if (n > 0) {
while (current != null) {
long result = current.skip(n);
if (result > 0) {
return result;
}
advance();
}
}
return 0;
}
@Override public boolean ready() throws IOException {
return (current != null) && current.ready();
}
@Override public void close() throws IOException {
if (current != null) {
try {
current.close();
} finally {
current = null;
}
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import java.io.IOException;
/**
* Package-protected abstract class that implements the line reading
* algorithm used by {@link LineReader}. Line separators are per {@link
* java.io.BufferedReader}: line feed, carriage return, or carriage
* return followed immediately by a linefeed.
*
* <p>Subclasses must implement {@link #handleLine}, call {@link #add}
* to pass character data, and call {@link #finish} at the end of stream.
*
* @author Chris Nokleberg
* @since 1.0
*/
abstract class LineBuffer {
/** Holds partial line contents. */
private StringBuilder line = new StringBuilder();
/** Whether a line ending with a CR is pending processing. */
private boolean sawReturn;
/**
* Process additional characters from the stream. When a line separator
* is found the contents of the line and the line separator itself
* are passed to the abstract {@link #handleLine} method.
*
* @param cbuf the character buffer to process
* @param off the offset into the buffer
* @param len the number of characters to process
* @throws IOException if an I/O error occurs
* @see #finish
*/
protected void add(char[] cbuf, int off, int len) throws IOException {
int pos = off;
if (sawReturn && len > 0) {
// Last call to add ended with a CR; we can handle the line now.
if (finishLine(cbuf[pos] == '\n')) {
pos++;
}
}
int start = pos;
for (int end = off + len; pos < end; pos++) {
switch (cbuf[pos]) {
case '\r':
line.append(cbuf, start, pos - start);
sawReturn = true;
if (pos + 1 < end) {
if (finishLine(cbuf[pos + 1] == '\n')) {
pos++;
}
}
start = pos + 1;
break;
case '\n':
line.append(cbuf, start, pos - start);
finishLine(true);
start = pos + 1;
break;
}
}
line.append(cbuf, start, off + len - start);
}
/** Called when a line is complete. */
private boolean finishLine(boolean sawNewline) throws IOException {
handleLine(line.toString(), sawReturn
? (sawNewline ? "\r\n" : "\r")
: (sawNewline ? "\n" : ""));
line = new StringBuilder();
sawReturn = false;
return sawNewline;
}
/**
* Subclasses must call this method after finishing character processing,
* in order to ensure that any unterminated line in the buffer is
* passed to {@link #handleLine}.
*
* @throws IOException if an I/O error occurs
*/
protected void finish() throws IOException {
if (sawReturn || line.length() > 0) {
finishLine(false);
}
}
/**
* Called for each line found in the character data passed to
* {@link #add}.
*
* @param line a line of text (possibly empty), without any line separators
* @param end the line separator; one of {@code "\r"}, {@code "\n"},
* {@code "\r\n"}, or {@code ""}
* @throws IOException if an I/O error occurs
*/
protected abstract void handleLine(String line, String end)
throws IOException;
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.LinkedList;
import java.util.Queue;
/**
* A class for reading lines of text. Provides the same functionality
* as {@link java.io.BufferedReader#readLine()} but for all {@link Readable}
* objects, not just instances of {@link Reader}.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class LineReader {
private final Readable readable;
private final Reader reader;
private final char[] buf = new char[0x1000]; // 4K
private final CharBuffer cbuf = CharBuffer.wrap(buf);
private final Queue<String> lines = new LinkedList<String>();
private final LineBuffer lineBuf = new LineBuffer() {
@Override protected void handleLine(String line, String end) {
lines.add(line);
}
};
/**
* Creates a new instance that will read lines from the given
* {@code Readable} object.
*/
public LineReader(Readable readable) {
Preconditions.checkNotNull(readable);
this.readable = readable;
this.reader = (readable instanceof Reader) ? (Reader) readable : null;
}
/**
* Reads a line of text. A line is considered to be terminated by any
* one of a line feed ({@code '\n'}), a carriage return
* ({@code '\r'}), or a carriage return followed immediately by a linefeed
* ({@code "\r\n"}).
*
* @return a {@code String} containing the contents of the line, not
* including any line-termination characters, or {@code null} if the
* end of the stream has been reached.
* @throws IOException if an I/O error occurs
*/
public String readLine() throws IOException {
while (lines.peek() == null) {
cbuf.clear();
// The default implementation of Reader#read(CharBuffer) allocates a
// temporary char[], so we call Reader#read(char[], int, int) instead.
int read = (reader != null)
? reader.read(buf, 0, buf.length)
: readable.read(cbuf);
if (read == -1) {
lineBuf.finish();
break;
}
lineBuf.add(buf, 0, read);
}
return lines.poll();
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Checksum;
/**
* Provides utility methods for working with files.
*
* <p>All method parameters must be non-null unless documented otherwise.
*
* @author Chris Nokleberg
* @since 1.0
*/
@Beta
public final class Files {
/** Maximum loop count when creating temp directories. */
private static final int TEMP_DIR_ATTEMPTS = 10000;
private Files() {}
/**
* Returns a buffered reader that reads from a file using the given
* character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return the buffered reader
*/
public static BufferedReader newReader(File file, Charset charset)
throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedReader(
new InputStreamReader(new FileInputStream(file), charset));
}
/**
* Returns a buffered writer that writes to a file using the given
* character set.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @return the buffered writer
*/
public static BufferedWriter newWriter(File file, Charset charset)
throws FileNotFoundException {
checkNotNull(file);
checkNotNull(charset);
return new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), charset));
}
/**
* Returns a factory that will supply instances of {@link FileInputStream}
* that read from a file.
*
* @param file the file to read from
* @return the factory
*/
public static InputSupplier<FileInputStream> newInputStreamSupplier(
final File file) {
checkNotNull(file);
return new InputSupplier<FileInputStream>() {
@Override
public FileInputStream getInput() throws IOException {
return new FileInputStream(file);
}
};
}
/**
* Returns a factory that will supply instances of {@link FileOutputStream}
* that write to a file.
*
* @param file the file to write to
* @return the factory
*/
public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(
File file) {
checkNotNull(file);
return newOutputStreamSupplier(file, false);
}
/**
* Returns a factory that will supply instances of {@link FileOutputStream}
* that write to or append to a file.
*
* @param file the file to write to
* @param append if true, the encoded characters will be appended to the file;
* otherwise the file is overwritten
* @return the factory
*/
public static OutputSupplier<FileOutputStream> newOutputStreamSupplier(
final File file, final boolean append) {
checkNotNull(file);
return new OutputSupplier<FileOutputStream>() {
@Override
public FileOutputStream getOutput() throws IOException {
return new FileOutputStream(file, append);
}
};
}
/**
* Returns a factory that will supply instances of
* {@link InputStreamReader} that read a file using the given character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return the factory
*/
public static InputSupplier<InputStreamReader> newReaderSupplier(File file,
Charset charset) {
checkNotNull(file);
checkNotNull(charset);
return CharStreams.newReaderSupplier(newInputStreamSupplier(file), charset);
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter}
* that write to a file using the given character set.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
Charset charset) {
checkNotNull(file);
checkNotNull(charset);
return newWriterSupplier(file, charset, false);
}
/**
* Returns a factory that will supply instances of {@link OutputStreamWriter}
* that write to or append to a file using the given character set.
*
* @param file the file to write to
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @param append if true, the encoded characters will be appended to the file;
* otherwise the file is overwritten
* @return the factory
*/
public static OutputSupplier<OutputStreamWriter> newWriterSupplier(File file,
Charset charset, boolean append) {
checkNotNull(file);
checkNotNull(charset);
return CharStreams.newWriterSupplier(
newOutputStreamSupplier(file, append), charset);
}
/**
* Reads all bytes from a file into a byte array.
*
* @param file the file to read from
* @return a byte array containing all the bytes from file
* @throws IllegalArgumentException if the file is bigger than the largest
* possible byte array (2^31 - 1)
* @throws IOException if an I/O error occurs
*/
public static byte[] toByteArray(File file) throws IOException {
checkNotNull(file);
checkArgument(file.length() <= Integer.MAX_VALUE);
if (file.length() == 0) {
// Some special files are length 0 but have content nonetheless.
return ByteStreams.toByteArray(newInputStreamSupplier(file));
} else {
// Avoid an extra allocation and copy.
byte[] b = new byte[(int) file.length()];
boolean threw = true;
InputStream in = new FileInputStream(file);
try {
ByteStreams.readFully(in, b);
threw = false;
} finally {
Closeables.close(in, threw);
}
return b;
}
}
/**
* Reads all characters from a file into a {@link String}, using the given
* character set.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return a string containing all the characters from the file
* @throws IOException if an I/O error occurs
*/
public static String toString(File file, Charset charset) throws IOException {
checkNotNull(file);
checkNotNull(charset);
return new String(toByteArray(file), charset.name());
}
/**
* Copies to a file all bytes from an {@link InputStream} supplied by a
* factory.
*
* @param from the input factory
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
public static void copy(InputSupplier<? extends InputStream> from, File to)
throws IOException {
checkNotNull(from);
checkNotNull(to);
ByteStreams.copy(from, newOutputStreamSupplier(to));
}
/**
* Overwrites a file with the contents of a byte array.
*
* @param from the bytes to write
* @param to the destination file
* @throws IOException if an I/O error occurs
*/
public static void write(byte[] from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
ByteStreams.write(from, newOutputStreamSupplier(to));
}
/**
* Copies all bytes from a file to an {@link OutputStream} supplied by
* a factory.
*
* @param from the source file
* @param to the output factory
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, OutputSupplier<? extends OutputStream> to)
throws IOException {
checkNotNull(from);
checkNotNull(to);
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Copies all bytes from a file to an output stream.
*
* @param from the source file
* @param to the output stream
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, OutputStream to) throws IOException {
checkNotNull(from);
checkNotNull(to);
ByteStreams.copy(newInputStreamSupplier(from), to);
}
/**
* Copies all the bytes from one file to another.
*
* <p><b>Warning:</b> If {@code to} represents an existing file, that file
* will be overwritten with the contents of {@code from}. If {@code to} and
* {@code from} refer to the <i>same</i> file, the contents of that file
* will be deleted.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void copy(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to),
"Source %s and destination %s must be different", from, to);
copy(newInputStreamSupplier(from), to);
}
/**
* Copies to a file all characters from a {@link Readable} and
* {@link Closeable} object supplied by a factory, using the given
* character set.
*
* @param from the readable supplier
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @throws IOException if an I/O error occurs
*/
public static <R extends Readable & Closeable> void copy(
InputSupplier<R> from, File to, Charset charset) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkNotNull(charset);
CharStreams.copy(from, newWriterSupplier(to, charset));
}
/**
* Writes a character sequence (such as a string) to a file using the given
* character set.
*
* @param from the character sequence to write
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @throws IOException if an I/O error occurs
*/
public static void write(CharSequence from, File to, Charset charset)
throws IOException {
checkNotNull(from);
checkNotNull(to);
checkNotNull(charset);
write(from, to, charset, false);
}
/**
* Appends a character sequence (such as a string) to a file using the given
* character set.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @throws IOException if an I/O error occurs
*/
public static void append(CharSequence from, File to, Charset charset)
throws IOException {
checkNotNull(from);
checkNotNull(to);
checkNotNull(charset);
write(from, to, charset, true);
}
/**
* Private helper method. Writes a character sequence to a file,
* optionally appending.
*
* @param from the character sequence to append
* @param to the destination file
* @param charset the charset used to encode the output stream; see {@link
* Charsets} for helpful predefined constants
* @param append true to append, false to overwrite
* @throws IOException if an I/O error occurs
*/
private static void write(CharSequence from, File to, Charset charset,
boolean append) throws IOException {
CharStreams.write(from, newWriterSupplier(to, charset, append));
}
/**
* Copies all characters from a file to a {@link Appendable} &
* {@link Closeable} object supplied by a factory, using the given
* character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @param to the appendable supplier
* @throws IOException if an I/O error occurs
*/
public static <W extends Appendable & Closeable> void copy(File from,
Charset charset, OutputSupplier<W> to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkNotNull(charset);
CharStreams.copy(newReaderSupplier(from, charset), to);
}
/**
* Copies all characters from a file to an appendable object,
* using the given character set.
*
* @param from the source file
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @param to the appendable object
* @throws IOException if an I/O error occurs
*/
public static void copy(File from, Charset charset, Appendable to)
throws IOException {
checkNotNull(from);
checkNotNull(to);
checkNotNull(charset);
CharStreams.copy(newReaderSupplier(from, charset), to);
}
/**
* Returns true if the files contains the same bytes.
*
* @throws IOException if an I/O error occurs
*/
public static boolean equal(File file1, File file2) throws IOException {
checkNotNull(file1);
checkNotNull(file2);
if (file1 == file2 || file1.equals(file2)) {
return true;
}
/*
* Some operating systems may return zero as the length for files
* denoting system-dependent entities such as devices or pipes, in
* which case we must fall back on comparing the bytes directly.
*/
long len1 = file1.length();
long len2 = file2.length();
if (len1 != 0 && len2 != 0 && len1 != len2) {
return false;
}
return ByteStreams.equal(newInputStreamSupplier(file1),
newInputStreamSupplier(file2));
}
/**
* Atomically creates a new directory somewhere beneath the system's
* temporary directory (as defined by the {@code java.io.tmpdir} system
* property), and returns its name.
*
* <p>Use this method instead of {@link File#createTempFile(String, String)}
* when you wish to create a directory, not a regular file. A common pitfall
* is to call {@code createTempFile}, delete the file and create a
* directory in its place, but this leads a race condition which can be
* exploited to create security vulnerabilities, especially when executable
* files are to be written into the directory.
*
* <p>This method assumes that the temporary volume is writable, has free
* inodes and free blocks, and that it will not be called thousands of times
* per second.
*
* @return the newly-created directory
* @throws IllegalStateException if the directory could not be created
*/
public static File createTempDir() {
File baseDir = new File(System.getProperty("java.io.tmpdir"));
String baseName = System.currentTimeMillis() + "-";
for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) {
File tempDir = new File(baseDir, baseName + counter);
if (tempDir.mkdir()) {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')');
}
/**
* Creates an empty file or updates the last updated timestamp on the
* same as the unix command of the same name.
*
* @param file the file to create or update
* @throws IOException if an I/O error occurs
*/
public static void touch(File file) throws IOException {
checkNotNull(file);
if (!file.createNewFile()
&& !file.setLastModified(System.currentTimeMillis())) {
throw new IOException("Unable to update modification time of " + file);
}
}
/**
* Creates any necessary but nonexistent parent directories of the specified
* file. Note that if this operation fails it may have succeeded in creating
* some (but not all) of the necessary parent directories.
*
* @throws IOException if an I/O error occurs, or if any necessary but
* nonexistent parent directories of the specified file could not be
* created.
* @since 4.0
*/
public static void createParentDirs(File file) throws IOException {
checkNotNull(file);
File parent = file.getCanonicalFile().getParentFile();
if (parent == null) {
/*
* The given directory is a filesystem root. All zero of its ancestors
* exist. This doesn't mean that the root itself exists -- consider x:\ on
* a Windows machine without such a drive -- or even that the caller can
* create it, but this method makes no such guarantees even for non-root
* files.
*/
return;
}
parent.mkdirs();
if (!parent.isDirectory()) {
throw new IOException("Unable to create parent directories of " + file);
}
}
/**
* Moves the file from one path to another. This method can rename a file or
* move it to a different directory, like the Unix {@code mv} command.
*
* @param from the source file
* @param to the destination file
* @throws IOException if an I/O error occurs
* @throws IllegalArgumentException if {@code from.equals(to)}
*/
public static void move(File from, File to) throws IOException {
checkNotNull(from);
checkNotNull(to);
checkArgument(!from.equals(to),
"Source %s and destination %s must be different", from, to);
if (!from.renameTo(to)) {
copy(from, to);
if (!from.delete()) {
if (!to.delete()) {
throw new IOException("Unable to delete " + to);
}
throw new IOException("Unable to delete " + from);
}
}
}
/**
* Reads the first line from a file. The line does not include
* line-termination characters, but does include other leading and
* trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return the first line, or null if the file is empty
* @throws IOException if an I/O error occurs
*/
public static String readFirstLine(File file, Charset charset)
throws IOException {
checkNotNull(file);
checkNotNull(charset);
return CharStreams.readFirstLine(Files.newReaderSupplier(file, charset));
}
/**
* Reads all of the lines from a file. The lines do not include
* line-termination characters, but do include other leading and
* trailing whitespace.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @return a mutable {@link List} containing all the lines
* @throws IOException if an I/O error occurs
*/
public static List<String> readLines(File file, Charset charset)
throws IOException {
checkNotNull(file);
checkNotNull(charset);
return CharStreams.readLines(Files.newReaderSupplier(file, charset));
}
/**
* Streams lines from a {@link File}, stopping when our callback returns
* false, or we have read all of the lines.
*
* @param file the file to read from
* @param charset the charset used to decode the input stream; see {@link
* Charsets} for helpful predefined constants
* @param callback the {@link LineProcessor} to use to handle the lines
* @return the output of processing the lines
* @throws IOException if an I/O error occurs
*/
public static <T> T readLines(File file, Charset charset,
LineProcessor<T> callback) throws IOException {
checkNotNull(file);
checkNotNull(charset);
checkNotNull(callback);
return CharStreams.readLines(
Files.newReaderSupplier(file, charset), callback);
}
/**
* Process the bytes of a file.
*
* <p>(If this seems too complicated, maybe you're looking for
* {@link #toByteArray}.)
*
* @param file the file to read
* @param processor the object to which the bytes of the file are passed.
* @return the result of the byte processor
* @throws IOException if an I/O error occurs
*/
public static <T> T readBytes(File file, ByteProcessor<T> processor)
throws IOException {
checkNotNull(file);
checkNotNull(processor);
return ByteStreams.readBytes(newInputStreamSupplier(file), processor);
}
/**
* Computes and returns the checksum value for a file.
* The checksum object is reset when this method returns successfully.
*
* @param file the file to read
* @param checksum the checksum object
* @return the result of {@link Checksum#getValue} after updating the
* checksum object with all of the bytes in the file
* @throws IOException if an I/O error occurs
*/
public static long getChecksum(File file, Checksum checksum)
throws IOException {
checkNotNull(file);
checkNotNull(checksum);
return ByteStreams.getChecksum(newInputStreamSupplier(file), checksum);
}
/**
* Computes the hash code of the {@code file} using {@code hashFunction}.
*
* @param file the file to read
* @param hashFunction the hash function to use to hash the data
* @return the {@link HashCode} of all of the bytes in the file
* @throws IOException if an I/O error occurs
* @since 12.0
*/
public static HashCode hash(File file, HashFunction hashFunction)
throws IOException {
checkNotNull(file);
checkNotNull(hashFunction);
return ByteStreams.hash(newInputStreamSupplier(file), hashFunction);
}
/**
* Fully maps a file read-only in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @return a read-only buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file) throws IOException {
checkNotNull(file);
return map(file, MapMode.READ_ONLY);
}
/**
* Fully maps a file in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}
* using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to its length.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws FileNotFoundException if the {@code file} does not exist
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode)
throws IOException {
checkNotNull(file);
checkNotNull(mode);
if (!file.exists()) {
throw new FileNotFoundException(file.toString());
}
return map(file, mode, file.length());
}
/**
* Maps a file in to memory as per
* {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}
* using the requested {@link MapMode}.
*
* <p>Files are mapped from offset 0 to {@code size}.
*
* <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist,
* it will be created with the requested {@code size}. Thus this method is
* useful for creating memory mapped files which do not yet exist.
*
* <p>This only works for files <= {@link Integer#MAX_VALUE} bytes.
*
* @param file the file to map
* @param mode the mode to use when mapping {@code file}
* @return a buffer reflecting {@code file}
* @throws IOException if an I/O error occurs
*
* @see FileChannel#map(MapMode, long, long)
* @since 2.0
*/
public static MappedByteBuffer map(File file, MapMode mode, long size)
throws FileNotFoundException, IOException {
checkNotNull(file);
checkNotNull(mode);
RandomAccessFile raf =
new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw");
boolean threw = true;
try {
MappedByteBuffer mbb = map(raf, mode, size);
threw = false;
return mbb;
} finally {
Closeables.close(raf, threw);
}
}
private static MappedByteBuffer map(RandomAccessFile raf, MapMode mode,
long size) throws IOException {
FileChannel channel = raf.getChannel();
boolean threw = true;
try {
MappedByteBuffer mbb = channel.map(mode, 0, size);
threw = false;
return mbb;
} finally {
Closeables.close(channel, threw);
}
}
/**
* Returns the lexically cleaned form of the path name, <i>usually</i> (but
* not always) equivalent to the original. The following heuristics are used:
*
* <ul>
* <li>empty string becomes .
* <li>. stays as .
* <li>fold out ./
* <li>fold out ../ when possible
* <li>collapse multiple slashes
* <li>delete trailing slashes (unless the path is just "/")
* </ul>
*
* These heuristics do not always match the behavior of the filesystem. In
* particular, consider the path {@code a/../b}, which {@code simplifyPath}
* will change to {@code b}. If {@code a} is a symlink to {@code x}, {@code
* a/../b} may refer to a sibling of {@code x}, rather than the sibling of
* {@code a} referred to by {@code b}.
*
* @since 11.0
*/
public static String simplifyPath(String pathname) {
checkNotNull(pathname);
if (pathname.length() == 0) {
return ".";
}
// split the path apart
Iterable<String> components =
Splitter.on('/').omitEmptyStrings().split(pathname);
List<String> path = new ArrayList<String>();
// resolve ., .., and //
for (String component : components) {
if (component.equals(".")) {
continue;
} else if (component.equals("..")) {
if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) {
path.remove(path.size() - 1);
} else {
path.add("..");
}
} else {
path.add(component);
}
}
// put it back together
String result = Joiner.on('/').join(path);
if (pathname.charAt(0) == '/') {
result = "/" + result;
}
while (result.startsWith("/../")) {
result = result.substring(3);
}
if (result.equals("/..")) {
result = "/";
} else if ("".equals(result)) {
result = ".";
}
return result;
}
/**
* Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file
* extension</a> for the given file name, or the empty string if the file has
* no extension. The result does not include the '{@code .}'.
*
* @since 11.0
*/
public static String getFileExtension(String fullName) {
checkNotNull(fullName);
String fileName = new File(fullName).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1);
}
/**
* Returns the file name without its
* <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is
* similar to the {@code basename} unix command. The result does not include the '{@code .}'.
*
* @param file The name of the file to trim the extension from. This can be either a fully
* qualified file name (including a path) or just a file name.
* @return The file name without its path or extension.
* @since 14.0
*/
public static String getNameWithoutExtension(String file) {
checkNotNull(file);
String fileName = new File(file).getName();
int dotIndex = fileName.lastIndexOf('.');
return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex);
}
}
| Java |
/*
* Copyright (C) 2004 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.io;
import com.google.common.annotations.Beta;
import java.io.OutputStream;
/**
* Implementation of {@link OutputStream} that simply discards written bytes.
*
* @author Spencer Kimball
* @since 1.0
* @deprecated Use {@link ByteStreams#nullOutputStream} instead. This class is
* scheduled to be removed in Guava release 15.0.
*/
@Beta
@Deprecated
public final class NullOutputStream extends OutputStream {
/** Discards the specified byte. */
@Override public void write(int b) {
}
/** Discards the specified byte array. */
@Override public void write(byte[] b, int off, int len) {
}
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Common annotation types. This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
package com.google.common.annotations;
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on a type indicates that the type may be
* used with the
* <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT).
* When applied to a method, the return type of the method is GWT compatible.
* It's useful to indicate that an instance created by factory methods has a GWT
* serializable type. In the following example,
*
* <pre style="code">
* {@literal @}GwtCompatible
* class Lists {
* ...
* {@literal @}GwtCompatible(serializable = true)
* static <E> List<E> newArrayList(E... elements) {
* ...
* }
* }
* </pre>
* The return value of {@code Lists.newArrayList(E[])} has GWT
* serializable type. It is also useful in specifying contracts of interface
* methods. In the following example,
*
* <pre style="code">
* {@literal @}GwtCompatible
* interface ListFactory {
* ...
* {@literal @}GwtCompatible(serializable = true)
* <E> List<E> newArrayList(E... elements);
* }
* </pre>
* The {@code newArrayList(E[])} method of all implementations of {@code
* ListFactory} is expected to return a value with a GWT serializable type.
*
* <p>Note that a {@code GwtCompatible} type may have some {@link
* GwtIncompatible} methods.
*
* @author Charles Fry
* @author Hayward Chan
*/
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.TYPE, ElementType.METHOD })
@Documented
@GwtCompatible
public @interface GwtCompatible {
/**
* When {@code true}, the annotated type or the type of the method return
* value is GWT serializable.
*
* @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideServerCommunication.html#DevGuideSerializableTypes">
* Documentation about GWT serialization</a>
*/
boolean serializable() default false;
/**
* When {@code true}, the annotated type is emulated in GWT. The emulated
* source (also known as super-source) is different from the implementation
* used by the JVM.
*
* @see <a href="http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html#DevGuideModules">
* Documentation about GWT emulated source</a>
*/
boolean emulated() default false;
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The presence of this annotation on a method indicates that the method may
* <em>not</em> be used with the
* <a href="http://code.google.com/webtoolkit/">Google Web Toolkit</a> (GWT),
* even though its type is annotated as {@link GwtCompatible} and accessible in
* GWT. They can cause GWT compilation errors or simply unexpected exceptions
* when used in GWT.
*
* <p>Note that this annotation should only be applied to methods, fields, or
* inner classes of types which are annotated as {@link GwtCompatible}.
*
* @author Charles Fry
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.TYPE, ElementType.METHOD,
ElementType.CONSTRUCTOR, ElementType.FIELD })
@Documented
@GwtCompatible
public @interface GwtIncompatible {
/**
* Describes why the annotated element is incompatible with GWT. Since this is
* generally due to a dependence on a type/method which GWT doesn't support,
* it is sufficient to simply reference the unsupported type/method. E.g.
* "Class.isInstance".
*/
String value();
}
| Java |
/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.annotations;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Signifies that a public API (public class, method or field) is subject to
* incompatible changes, or even removal, in a future release. An API bearing
* this annotation is exempt from any compatibility guarantees made by its
* containing library. Note that the presence of this annotation implies nothing
* about the quality or performance of the API in question, only the fact that
* it is not "API-frozen."
*
* <p>It is generally safe for <i>applications</i> to depend on beta APIs, at
* the cost of some extra work during upgrades. However it is generally
* inadvisable for <i>libraries</i> (which get included on users' CLASSPATHs,
* outside the library developers' control) to do so.
*
*
* @author Kevin Bourrillion
*/
@Retention(RetentionPolicy.CLASS)
@Target({
ElementType.ANNOTATION_TYPE,
ElementType.CONSTRUCTOR,
ElementType.FIELD,
ElementType.METHOD,
ElementType.TYPE})
@Documented
@GwtCompatible
public @interface Beta {}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.annotations;
/**
* Annotates a program element that exists, or is more widely visible than
* otherwise necessary, only for use in test code.
*
* @author Johannes Henkel
*/
@GwtCompatible
public @interface VisibleForTesting {
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import javax.annotation.Nullable;
/**
* An abstract implementation of the {@link ListenableFuture} interface. This
* class is preferable to {@link java.util.concurrent.FutureTask} for two
* reasons: It implements {@code ListenableFuture}, and it does not implement
* {@code Runnable}. (If you want a {@code Runnable} implementation of {@code
* ListenableFuture}, create a {@link ListenableFutureTask}, or submit your
* tasks to a {@link ListeningExecutorService}.)
*
* <p>This class implements all methods in {@code ListenableFuture}.
* Subclasses should provide a way to set the result of the computation through
* the protected methods {@link #set(Object)} and
* {@link #setException(Throwable)}. Subclasses may also override {@link
* #interruptTask()}, which will be invoked automatically if a call to {@link
* #cancel(boolean) cancel(true)} succeeds in canceling the future.
*
* <p>{@code AbstractFuture} uses an {@link AbstractQueuedSynchronizer} to deal
* with concurrency issues and guarantee thread safety.
*
* <p>The state changing methods all return a boolean indicating success or
* failure in changing the future's state. Valid states are running,
* completed, failed, or cancelled.
*
* <p>This class uses an {@link ExecutionList} to guarantee that all registered
* listeners will be executed, either when the future finishes or, for listeners
* that are added after the future completes, immediately.
* {@code Runnable}-{@code Executor} pairs are stored in the execution list but
* are not necessarily executed in the order in which they were added. (If a
* listener is added after the Future is complete, it will be executed
* immediately, even if earlier listeners have not been executed. Additionally,
* executors need not guarantee FIFO execution, or different listeners may run
* in different executors.)
*
* @author Sven Mawson
* @since 1.0
*/
public abstract class AbstractFuture<V> implements ListenableFuture<V> {
/** Synchronization control for AbstractFutures. */
private final Sync<V> sync = new Sync<V>();
// The execution list to hold our executors.
private final ExecutionList executionList = new ExecutionList();
/**
* Constructor for use by subclasses.
*/
protected AbstractFuture() {}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get(long timeout, TimeUnit unit) throws InterruptedException,
TimeoutException, ExecutionException {
return sync.get(unit.toNanos(timeout));
}
/*
* Improve the documentation of when InterruptedException is thrown. Our
* behavior matches the JDK's, but the JDK's documentation is misleading.
*/
/**
* {@inheritDoc}
*
* <p>The default {@link AbstractFuture} implementation throws {@code
* InterruptedException} if the current thread is interrupted before or during
* the call, even if the value is already available.
*
* @throws InterruptedException if the current thread was interrupted before
* or during the call (optional but recommended).
* @throws CancellationException {@inheritDoc}
*/
@Override
public V get() throws InterruptedException, ExecutionException {
return sync.get();
}
@Override
public boolean isDone() {
return sync.isDone();
}
@Override
public boolean isCancelled() {
return sync.isCancelled();
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (!sync.cancel(mayInterruptIfRunning)) {
return false;
}
executionList.execute();
if (mayInterruptIfRunning) {
interruptTask();
}
return true;
}
/**
* Subclasses can override this method to implement interruption of the
* future's computation. The method is invoked automatically by a successful
* call to {@link #cancel(boolean) cancel(true)}.
*
* <p>The default implementation does nothing.
*
* @since 10.0
*/
protected void interruptTask() {
}
/**
* Returns true if this future was cancelled with {@code
* mayInterruptIfRunning} set to {@code true}.
*
* @since 14.0
*/
protected final boolean wasInterrupted() {
return sync.wasInterrupted();
}
/**
* {@inheritDoc}
*
* @since 10.0
*/
@Override
public void addListener(Runnable listener, Executor exec) {
executionList.add(listener, exec);
}
/**
* Subclasses should invoke this method to set the result of the computation
* to {@code value}. This will set the state of the future to
* {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
* state was successfully changed.
*
* @param value the value that was the result of the task.
* @return true if the state was successfully changed.
*/
protected boolean set(@Nullable V value) {
boolean result = sync.set(value);
if (result) {
executionList.execute();
}
return result;
}
/**
* Subclasses should invoke this method to set the result of the computation
* to an error, {@code throwable}. This will set the state of the future to
* {@link AbstractFuture.Sync#COMPLETED} and invoke the listeners if the
* state was successfully changed.
*
* @param throwable the exception that the task failed with.
* @return true if the state was successfully changed.
* @throws Error if the throwable was an {@link Error}.
*/
protected boolean setException(Throwable throwable) {
boolean result = sync.setException(checkNotNull(throwable));
if (result) {
executionList.execute();
}
// If it's an Error, we want to make sure it reaches the top of the
// call stack, so we rethrow it.
if (throwable instanceof Error) {
throw (Error) throwable;
}
return result;
}
/**
* <p>Following the contract of {@link AbstractQueuedSynchronizer} we create a
* private subclass to hold the synchronizer. This synchronizer is used to
* implement the blocking and waiting calls as well as to handle state changes
* in a thread-safe manner. The current state of the future is held in the
* Sync state, and the lock is released whenever the state changes to
* {@link #COMPLETED}, {@link #CANCELLED}, or {@link #INTERRUPTED}
*
* <p>To avoid races between threads doing release and acquire, we transition
* to the final state in two steps. One thread will successfully CAS from
* RUNNING to COMPLETING, that thread will then set the result of the
* computation, and only then transition to COMPLETED, CANCELLED, or
* INTERRUPTED.
*
* <p>We don't use the integer argument passed between acquire methods so we
* pass around a -1 everywhere.
*/
static final class Sync<V> extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 0L;
/* Valid states. */
static final int RUNNING = 0;
static final int COMPLETING = 1;
static final int COMPLETED = 2;
static final int CANCELLED = 4;
static final int INTERRUPTED = 8;
private V value;
private Throwable exception;
/*
* Acquisition succeeds if the future is done, otherwise it fails.
*/
@Override
protected int tryAcquireShared(int ignored) {
if (isDone()) {
return 1;
}
return -1;
}
/*
* We always allow a release to go through, this means the state has been
* successfully changed and the result is available.
*/
@Override
protected boolean tryReleaseShared(int finalState) {
setState(finalState);
return true;
}
/**
* Blocks until the task is complete or the timeout expires. Throws a
* {@link TimeoutException} if the timer expires, otherwise behaves like
* {@link #get()}.
*/
V get(long nanos) throws TimeoutException, CancellationException,
ExecutionException, InterruptedException {
// Attempt to acquire the shared lock with a timeout.
if (!tryAcquireSharedNanos(-1, nanos)) {
throw new TimeoutException("Timeout waiting for task.");
}
return getValue();
}
/**
* Blocks until {@link #complete(Object, Throwable, int)} has been
* successfully called. Throws a {@link CancellationException} if the task
* was cancelled, or a {@link ExecutionException} if the task completed with
* an error.
*/
V get() throws CancellationException, ExecutionException,
InterruptedException {
// Acquire the shared lock allowing interruption.
acquireSharedInterruptibly(-1);
return getValue();
}
/**
* Implementation of the actual value retrieval. Will return the value
* on success, an exception on failure, a cancellation on cancellation, or
* an illegal state if the synchronizer is in an invalid state.
*/
private V getValue() throws CancellationException, ExecutionException {
int state = getState();
switch (state) {
case COMPLETED:
if (exception != null) {
throw new ExecutionException(exception);
} else {
return value;
}
case CANCELLED:
case INTERRUPTED:
throw cancellationExceptionWithCause(
"Task was cancelled.", exception);
default:
throw new IllegalStateException(
"Error, synchronizer in invalid state: " + state);
}
}
/**
* Checks if the state is {@link #COMPLETED}, {@link #CANCELLED}, or {@link
* INTERRUPTED}.
*/
boolean isDone() {
return (getState() & (COMPLETED | CANCELLED | INTERRUPTED)) != 0;
}
/**
* Checks if the state is {@link #CANCELLED} or {@link #INTERRUPTED}.
*/
boolean isCancelled() {
return (getState() & (CANCELLED | INTERRUPTED)) != 0;
}
/**
* Checks if the state is {@link #INTERRUPTED}.
*/
boolean wasInterrupted() {
return getState() == INTERRUPTED;
}
/**
* Transition to the COMPLETED state and set the value.
*/
boolean set(@Nullable V v) {
return complete(v, null, COMPLETED);
}
/**
* Transition to the COMPLETED state and set the exception.
*/
boolean setException(Throwable t) {
return complete(null, t, COMPLETED);
}
/**
* Transition to the CANCELLED or INTERRUPTED state.
*/
boolean cancel(boolean interrupt) {
return complete(null, null, interrupt ? INTERRUPTED : CANCELLED);
}
/**
* Implementation of completing a task. Either {@code v} or {@code t} will
* be set but not both. The {@code finalState} is the state to change to
* from {@link #RUNNING}. If the state is not in the RUNNING state we
* return {@code false} after waiting for the state to be set to a valid
* final state ({@link #COMPLETED}, {@link #CANCELLED}, or {@link
* #INTERRUPTED}).
*
* @param v the value to set as the result of the computation.
* @param t the exception to set as the result of the computation.
* @param finalState the state to transition to.
*/
private boolean complete(@Nullable V v, @Nullable Throwable t,
int finalState) {
boolean doCompletion = compareAndSetState(RUNNING, COMPLETING);
if (doCompletion) {
// If this thread successfully transitioned to COMPLETING, set the value
// and exception and then release to the final state.
this.value = v;
// Don't actually construct a CancellationException until necessary.
this.exception = isCancelled()
? new CancellationException("Future.cancel() was called.") : t;
releaseShared(finalState);
} else if (getState() == COMPLETING) {
// If some other thread is currently completing the future, block until
// they are done so we can guarantee completion.
acquireShared(-1);
}
return doCompletion;
}
}
static final CancellationException cancellationExceptionWithCause(
String message, Throwable cause) {
CancellationException exception = new CancellationException(message);
exception.initCause(cause);
return exception;
}
}
| Java |
/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.base.Ticker;
import java.util.concurrent.TimeUnit;
import javax.annotation.concurrent.ThreadSafe;
/**
* A rate limiter. Conceptually, a rate limiter distributes permits at a
* configurable rate. Each {@link #acquire()} blocks if necessary until a permit is
* available, and then takes it. Once acquired, permits need not be released.
*
* <p>Rate limiters are often used to restrict the rate at which some
* physical or logical resource is accessed. This is in contrast to {@link
* java.util.concurrent.Semaphore} which restricts the number of concurrent
* accesses instead of the rate (note though that concurrency and rate are closely related,
* e.g. see <a href="http://en.wikipedia.org/wiki/Little's_law">Little's Law</a>).
*
* <p>A {@code RateLimiter} is defined primarily by the rate at which permits
* are issued. Absent additional configuration, permits will be distributed at a
* fixed rate, defined in terms of permits per second. Permits will be distributed
* smoothly, with the delay between individual permits being adjusted to ensure
* that the configured rate is maintained.
*
* <p>It is possible to configure a {@code RateLimiter} to have a warmup
* period during which time the permits issued each second steadily increases until
* it hits the stable rate.
*
* <p>As an example, imagine that we have a list of tasks to execute, but we don't want to
* submit more than 2 per second:
*<pre> {@code
* final RateLimiter rateLimiter = RateLimiter.create(2.0); // rate is "2 permits per second"
* void submitTasks(List<Runnable> tasks, Executor executor) {
* for (Runnable task : tasks) {
* rateLimiter.acquire(); // may wait
* executor.execute(task);
* }
* }
*}</pre>
*
* <p>As another example, imagine that we produce a stream of data, and we want to cap it
* at 5kb per second. This could be accomplished by requiring a permit per byte, and specifying
* a rate of 5000 permits per second:
*<pre> {@code
* final RateLimiter rateLimiter = RateLimiter.create(5000.0); // rate = 5000 permits per second
* void submitPacket(byte[] packet) {
* rateLimiter.acquire(packet.length);
* networkService.send(packet);
* }
*}</pre>
*
* <p>It is important to note that the number of permits requested <i>never</i>
* affect the throttling of the request itself (an invocation to {@code acquire(1)}
* and an invocation to {@code acquire(1000)} will result in exactly the same throttling, if any),
* but it affects the throttling of the <i>next</i> request. I.e., if an expensive task
* arrives at an idle RateLimiter, it will be granted immediately, but it is the <i>next</i>
* request that will experience extra throttling, thus paying for the cost of the expensive
* task.
*
* <p>Note: {@code RateLimiter} does not provide fairness guarantees.
*
* @author Dimitris Andreou
* @since 13.0
*/
// TODO(user): switch to nano precision. A natural unit of cost is "bytes", and a micro precision
// would mean a maximum rate of "1MB/s", which might be small in some cases.
@ThreadSafe
@Beta
public abstract class RateLimiter {
/*
* How is the RateLimiter designed, and why?
*
* The primary feature of a RateLimiter is its "stable rate", the maximum rate that
* is should allow at normal conditions. This is enforced by "throttling" incoming
* requests as needed, i.e. compute, for an incoming request, the appropriate throttle time,
* and make the calling thread wait as much.
*
* The simplest way to maintain a rate of QPS is to keep the timestamp of the last
* granted request, and ensure that (1/QPS) seconds have elapsed since then. For example,
* for a rate of QPS=5 (5 tokens per second), if we ensure that a request isn't granted
* earlier than 200ms after the the last one, then we achieve the intended rate.
* If a request comes and the last request was granted only 100ms ago, then we wait for
* another 100ms. At this rate, serving 15 fresh permits (i.e. for an acquire(15) request)
* naturally takes 3 seconds.
*
* It is important to realize that such a RateLimiter has a very superficial memory
* of the past: it only remembers the last request. What if the RateLimiter was unused for
* a long period of time, then a request arrived and was immediately granted?
* This RateLimiter would immediately forget about that past underutilization. This may
* result in either underutilization or overflow, depending on the real world consequences
* of not using the expected rate.
*
* Past underutilization could mean that excess resources are available. Then, the RateLimiter
* should speed up for a while, to take advantage of these resources. This is important
* when the rate is applied to networking (limiting bandwidth), where past underutilization
* typically translates to "almost empty buffers", which can be filled immediately.
*
* On the other hand, past underutilization could mean that "the server responsible for
* handling the request has become less ready for future requests", i.e. its caches become
* stale, and requests become more likely to trigger expensive operations (a more extreme
* case of this example is when a server has just booted, and it is mostly busy with getting
* itself up to speed).
*
* To deal with such scenarios, we add an extra dimension, that of "past underutilization",
* modeled by "storedPermits" variable. This variable is zero when there is no
* underutilization, and it can grow up to maxStoredPermits, for sufficiently large
* underutilization. So, the requested permits, by an invocation acquire(permits),
* are served from:
* - stored permits (if available)
* - fresh permits (for any remaining permits)
*
* How this works is best explained with an example:
*
* For a RateLimiter that produces 1 token per second, every second
* that goes by with the RateLimiter being unused, we increase storedPermits by 1.
* Say we leave the RateLimiter unused for 10 seconds (i.e., we expected a request at time
* X, but we are at time X + 10 seconds before a request actually arrives; this is
* also related to the point made in the last paragraph), thus storedPermits
* becomes 10.0 (assuming maxStoredPermits >= 10.0). At that point, a request of acquire(3)
* arrives. We serve this request out of storedPermits, and reduce that to 7.0 (how this is
* translated to throttling time is discussed later). Immediately after, assume that an
* acquire(10) request arriving. We serve the request partly from storedPermits,
* using all the remaining 7.0 permits, and the remaining 3.0, we serve them by fresh permits
* produced by the rate limiter.
*
* We already know how much time it takes to serve 3 fresh permits: if the rate is
* "1 token per second", then this will take 3 seconds. But what does it mean to serve 7
* stored permits? As explained above, there is no unique answer. If we are primarily
* interested to deal with underutilization, then we want stored permits to be given out
* /faster/ than fresh ones, because underutilization = free resources for the taking.
* If we are primarily interested to deal with overflow, then stored permits could
* be given out /slower/ than fresh ones. Thus, we require a (different in each case)
* function that translates storedPermits to throtting time.
*
* This role is played by storedPermitsToWaitTime(double storedPermits, double permitsToTake).
* The underlying model is a continuous function mapping storedPermits
* (from 0.0 to maxStoredPermits) onto the 1/rate (i.e. intervals) that is effective at the given
* storedPermits. "storedPermits" essentially measure unused time; we spend unused time
* buying/storing permits. Rate is "permits / time", thus "1 / rate = time / permits".
* Thus, "1/rate" (time / permits) times "permits" gives time, i.e., integrals on this
* function (which is what storedPermitsToWaitTime() computes) correspond to minimum intervals
* between subsequent requests, for the specified number of requested permits.
*
* Here is an example of storedPermitsToWaitTime:
* If storedPermits == 10.0, and we want 3 permits, we take them from storedPermits,
* reducing them to 7.0, and compute the throttling for these as a call to
* storedPermitsToWaitTime(storedPermits = 10.0, permitsToTake = 3.0), which will
* evaluate the integral of the function from 7.0 to 10.0.
*
* Using integrals guarantees that the effect of a single acquire(3) is equivalent
* to { acquire(1); acquire(1); acquire(1); }, or { acquire(2); acquire(1); }, etc,
* since the integral of the function in [7.0, 10.0] is equivalent to the sum of the
* integrals of [7.0, 8.0], [8.0, 9.0], [9.0, 10.0] (and so on), no matter
* what the function is. This guarantees that we handle correctly requests of varying weight
* (permits), /no matter/ what the actual function is - so we can tweak the latter freely.
* (The only requirement, obviously, is that we can compute its integrals).
*
* Note well that if, for this function, we chose a horizontal line, at height of exactly
* (1/QPS), then the effect of the function is non-existent: we serve storedPermits at
* exactly the same cost as fresh ones (1/QPS is the cost for each). We use this trick later.
*
* If we pick a function that goes /below/ that horizontal line, it means that we reduce
* the area of the function, thus time. Thus, the RateLimiter becomes /faster/ after a
* period of underutilization. If, on the other hand, we pick a function that
* goes /above/ that horizontal line, then it means that the area (time) is increased,
* thus storedPermits are more costly than fresh permits, thus the RateLimiter becomes
* /slower/ after a period of underutilization.
*
* Last, but not least: consider a RateLimiter with rate of 1 permit per second, currently
* completely unused, and an expensive acquire(100) request comes. It would be nonsensical
* to just wait for 100 seconds, and /then/ start the actual task. Why wait without doing
* anything? A much better approach is to /allow/ the request right away (as if it was an
* acquire(1) request instead), and postpone /subsequent/ requests as needed. In this version,
* we allow starting the task immediately, and postpone by 100 seconds future requests,
* thus we allow for work to get done in the meantime instead of waiting idly.
*
* This has important consequences: it means that the RateLimiter doesn't remember the time
* of the _last_ request, but it remembers the (expected) time of the _next_ request. This
* also enables us to tell immediately (see tryAcquire(timeout)) whether a particular
* timeout is enough to get us to the point of the next scheduling time, since we always
* maintain that. And what we mean by "an unused RateLimiter" is also defined by that
* notion: when we observe that the "expected arrival time of the next request" is actually
* in the past, then the difference (now - past) is the amount of time that the RateLimiter
* was formally unused, and it is that amount of time which we translate to storedPermits.
* (We increase storedPermits with the amount of permits that would have been produced
* in that idle time). So, if rate == 1 permit per second, and arrivals come exactly
* one second after the previous, then storedPermits is _never_ increased -- we would only
* increase it for arrivals _later_ than the expected one second.
*/
/**
* Creates a {@code RateLimiter} with the specified stable throughput, given as
* "permits per second" (commonly referred to as <i>QPS</i>, queries per second).
*
* <p>The returned {@code RateLimiter} ensures that on average no more than {@code
* permitsPerSecond} are issued during any given second, with sustained requests
* being smoothly spread over each second. When the incoming request rate exceeds
* {@code permitsPerSecond} the rate limiter will release one permit every {@code
* (1.0 / permitsPerSecond)} seconds. When the rate limiter is unused,
* bursts of up to {@code permitsPerSecond} permits will be allowed, with subsequent
* requests being smoothly limited at the stable rate of {@code permitsPerSecond}.
*
* @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in
* how many permits become available per second.
*/
public static RateLimiter create(double permitsPerSecond) {
return create(SleepingTicker.SYSTEM_TICKER, permitsPerSecond);
}
@VisibleForTesting
static RateLimiter create(SleepingTicker ticker, double permitsPerSecond) {
RateLimiter rateLimiter = new Bursty(ticker);
rateLimiter.setRate(permitsPerSecond);
return rateLimiter;
}
/**
* Creates a {@code RateLimiter} with the specified stable throughput, given as
* "permits per second" (commonly referred to as <i>QPS</i>, queries per second), and a
* <i>warmup period</i>, during which the {@code RateLimiter} smoothly ramps up its rate,
* until it reaches its maximum rate at the end of the period (as long as there are enough
* requests to saturate it). Similarly, if the {@code RateLimiter} is left <i>unused</i> for
* a duration of {@code warmupPeriod}, it will gradually return to its "cold" state,
* i.e. it will go through the same warming up process as when it was first created.
*
* <p>The returned {@code RateLimiter} is intended for cases where the resource that actually
* fulfils the requests (e.g., a remote server) needs "warmup" time, rather than
* being immediately accessed at the stable (maximum) rate.
*
* <p>The returned {@code RateLimiter} starts in a "cold" state (i.e. the warmup period
* will follow), and if it is left unused for long enough, it will return to that state.
*
* @param permitsPerSecond the rate of the returned {@code RateLimiter}, measured in
* how many permits become available per second
* @param warmupPeriod the duration of the period where the {@code RateLimiter} ramps up its
* rate, before reaching its stable (maximum) rate
* @param unit the time unit of the warmupPeriod argument
*/
// TODO(user): add a burst size of 1-second-worth of permits, as in the metronome?
public static RateLimiter create(double permitsPerSecond, long warmupPeriod, TimeUnit unit) {
return create(SleepingTicker.SYSTEM_TICKER, permitsPerSecond, warmupPeriod, unit);
}
@VisibleForTesting
static RateLimiter create(
SleepingTicker ticker, double permitsPerSecond, long warmupPeriod, TimeUnit timeUnit) {
RateLimiter rateLimiter = new WarmingUp(ticker, warmupPeriod, timeUnit);
rateLimiter.setRate(permitsPerSecond);
return rateLimiter;
}
@VisibleForTesting
static RateLimiter createBursty(
SleepingTicker ticker, double permitsPerSecond, int maxBurstSize) {
Bursty rateLimiter = new Bursty(ticker);
rateLimiter.setRate(permitsPerSecond);
rateLimiter.maxPermits = maxBurstSize;
return rateLimiter;
}
/**
* The underlying timer; used both to measure elapsed time and sleep as necessary. A separate
* object to facilitate testing.
*/
private final SleepingTicker ticker;
/**
* The timestamp when the RateLimiter was created; used to avoid possible overflow/time-wrapping
* errors.
*/
private final long offsetNanos;
/**
* The currently stored permits.
*/
double storedPermits;
/**
* The maximum number of stored permits.
*/
double maxPermits;
/**
* The interval between two unit requests, at our stable rate. E.g., a stable rate of 5 permits
* per second has a stable interval of 200ms.
*/
double stableIntervalMicros;
/**
* The time when the next request (no matter its size) will be granted. After granting a request,
* this is pushed further in the future. Large requests push this further than small requests.
*/
private long nextFreeTicketMicros = 0L; // could be either in the past or future
private RateLimiter(SleepingTicker ticker) {
this.ticker = ticker;
this.offsetNanos = ticker.read();
}
/**
* Updates the stable rate of this {@code RateLimiter}, that is, the
* {@code permitsPerSecond} argument provided in the factory method that
* constructed the {@code RateLimiter}. Currently throttled threads will <b>not</b>
* be awakened as a result of this invocation, thus they do not observe the new rate;
* only subsequent requests will.
*
* <p>Note though that, since each request repays (by waiting, if necessary) the cost
* of the <i>previous</i> request, this means that the very next request
* after an invocation to {@code setRate} will not be affected by the new rate;
* it will pay the cost of the previous request, which is in terms of the previous rate.
*
* <p>The behavior of the {@code RateLimiter} is not modified in any other way,
* e.g. if the {@code RateLimiter} was configured with a warmup period of 20 seconds,
* it still has a warmup period of 20 seconds after this method invocation.
*
* @param permitsPerSecond the new stable rate of this {@code RateLimiter}.
*/
public final synchronized void setRate(double permitsPerSecond) {
Preconditions.checkArgument(permitsPerSecond > 0.0
&& !Double.isNaN(permitsPerSecond), "rate must be positive");
resync(readSafeMicros());
double stableIntervalMicros = TimeUnit.SECONDS.toMicros(1L) / permitsPerSecond;
this.stableIntervalMicros = stableIntervalMicros;
doSetRate(permitsPerSecond, stableIntervalMicros);
}
abstract void doSetRate(double permitsPerSecond, double stableIntervalMicros);
/**
* Returns the stable rate (as {@code permits per seconds}) with which this
* {@code RateLimiter} is configured with. The initial value of this is the same as
* the {@code permitsPerSecond} argument passed in the factory method that produced
* this {@code RateLimiter}, and it is only updated after invocations
* to {@linkplain #setRate}.
*/
public final synchronized double getRate() {
return TimeUnit.SECONDS.toMicros(1L) / stableIntervalMicros;
}
/**
* Acquires a permit from this {@code RateLimiter}, blocking until the request can be granted.
*
* <p>This method is equivalent to {@code acquire(1)}.
*/
public void acquire() {
acquire(1);
}
/**
* Acquires the given number of permits from this {@code RateLimiter}, blocking until the
* request be granted.
*
* @param permits the number of permits to acquire
*/
public void acquire(int permits) {
checkPermits(permits);
long microsToWait;
synchronized (this) {
microsToWait = reserveNextTicket(permits, readSafeMicros());
}
ticker.sleepMicrosUninterruptibly(microsToWait);
}
/**
* Acquires a permit from this {@code RateLimiter} if it can be obtained
* without exceeding the specified {@code timeout}, or returns {@code false}
* immediately (without waiting) if the permit would not have been granted
* before the timeout expired.
*
* <p>This method is equivalent to {@code tryAcquire(1, timeout, unit)}.
*
* @param timeout the maximum time to wait for the permit
* @param unit the time unit of the timeout argument
* @return {@code true} if the permit was acquired, {@code false} otherwise
*/
public boolean tryAcquire(long timeout, TimeUnit unit) {
return tryAcquire(1, timeout, unit);
}
/**
* Acquires permits from this {@link RateLimiter} if it can be acquired immediately without delay.
*
* <p>
* This method is equivalent to {@code tryAcquire(permits, 0, anyUnit)}.
*
* @param permits the number of permits to acquire
* @return {@code true} if the permits were acquired, {@code false} otherwise
* @since 14.0
*/
public boolean tryAcquire(int permits) {
return tryAcquire(permits, 0, TimeUnit.MICROSECONDS);
}
/**
* Acquires a permit from this {@link RateLimiter} if it can be acquired immediately without
* delay.
*
* <p>
* This method is equivalent to {@code tryAcquire(1)}.
*
* @return {@code true} if the permit was acquired, {@code false} otherwise
* @since 14.0
*/
public boolean tryAcquire() {
return tryAcquire(1, 0, TimeUnit.MICROSECONDS);
}
/**
* Acquires the given number of permits from this {@code RateLimiter} if it can be obtained
* without exceeding the specified {@code timeout}, or returns {@code false}
* immediately (without waiting) if the permits would not have been granted
* before the timeout expired.
*
* @param permits the number of permits to acquire
* @param timeout the maximum time to wait for the permits
* @param unit the time unit of the timeout argument
* @return {@code true} if the permits were acquired, {@code false} otherwise
*/
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) {
checkPermits(permits);
long timeoutMicros = unit.toMicros(timeout);
long microsToWait;
synchronized (this) {
long nowMicros = readSafeMicros();
if (nextFreeTicketMicros > nowMicros + timeoutMicros) {
return false;
} else {
microsToWait = reserveNextTicket(permits, nowMicros);
}
}
ticker.sleepMicrosUninterruptibly(microsToWait);
return true;
}
private static void checkPermits(int permits) {
Preconditions.checkArgument(permits > 0, "Requested permits must be positive");
}
/**
* Reserves next ticket and returns the wait time that the caller must wait for.
*/
private long reserveNextTicket(double requiredPermits, long nowMicros) {
resync(nowMicros);
long microsToNextFreeTicket = nextFreeTicketMicros - nowMicros;
double storedPermitsToSpend = Math.min(requiredPermits, this.storedPermits);
double freshPermits = requiredPermits - storedPermitsToSpend;
long waitMicros = storedPermitsToWaitTime(this.storedPermits, storedPermitsToSpend)
+ (long) (freshPermits * stableIntervalMicros);
this.nextFreeTicketMicros = nextFreeTicketMicros + waitMicros;
this.storedPermits -= storedPermitsToSpend;
return microsToNextFreeTicket;
}
/**
* Translates a specified portion of our currently stored permits which we want to
* spend/acquire, into a throttling time. Conceptually, this evaluates the integral
* of the underlying function we use, for the range of
* [(storedPermits - permitsToTake), storedPermits].
*
* This always holds: {@code 0 <= permitsToTake <= storedPermits}
*/
abstract long storedPermitsToWaitTime(double storedPermits, double permitsToTake);
private void resync(long nowMicros) {
// if nextFreeTicket is in the past, resync to now
if (nowMicros > nextFreeTicketMicros) {
storedPermits = Math.min(maxPermits,
storedPermits + (nowMicros - nextFreeTicketMicros) / stableIntervalMicros);
nextFreeTicketMicros = nowMicros;
}
}
private long readSafeMicros() {
return TimeUnit.NANOSECONDS.toMicros(ticker.read() - offsetNanos);
}
@Override
public String toString() {
return String.format("RateLimiter[stableRate=%3.1fqps]", 1000000.0 / stableIntervalMicros);
}
/**
* This implements the following function:
*
* ^ throttling
* |
* 3*stable + /
* interval | /.
* (cold) | / .
* | / . <-- "warmup period" is the area of the trapezoid between
* 2*stable + / . halfPermits and maxPermits
* interval | / .
* | / .
* | / .
* stable +----------/ WARM . }
* interval | . UP . } <-- this rectangle (from 0 to maxPermits, and
* | . PERIOD. } height == stableInterval) defines the cooldown period,
* | . . } and we want cooldownPeriod == warmupPeriod
* |---------------------------------> storedPermits
* (halfPermits) (maxPermits)
*
* Before going into the details of this particular function, let's keep in mind the basics:
* 1) The state of the RateLimiter (storedPermits) is a vertical line in this figure.
* 2) When the RateLimiter is not used, this goes right (up to maxPermits)
* 3) When the RateLimiter is used, this goes left (down to zero), since if we have storedPermits,
* we serve from those first
* 4) When _unused_, we go right at the same speed (rate)! I.e., if our rate is
* 2 permits per second, and 3 unused seconds pass, we will always save 6 permits
* (no matter what our initial position was), up to maxPermits.
* If we invert the rate, we get the "stableInterval" (interval between two requests
* in a perfectly spaced out sequence of requests of the given rate). Thus, if you
* want to see "how much time it will take to go from X storedPermits to X+K storedPermits?",
* the answer is always stableInterval * K. In the same example, for 2 permits per second,
* stableInterval is 500ms. Thus to go from X storedPermits to X+6 storedPermits, we
* require 6 * 500ms = 3 seconds.
*
* In short, the time it takes to move to the right (save K permits) is equal to the
* rectangle of width == K and height == stableInterval.
* 4) When _used_, the time it takes, as explained in the introductory class note, is
* equal to the integral of our function, between X permits and X-K permits, assuming
* we want to spend K saved permits.
*
* In summary, the time it takes to move to the left (spend K permits), is equal to the
* area of the function of width == K.
*
* Let's dive into this function now:
*
* When we have storedPermits <= halfPermits (the left portion of the function), then
* we spend them at the exact same rate that
* fresh permits would be generated anyway (that rate is 1/stableInterval). We size
* this area to be equal to _half_ the specified warmup period. Why we need this?
* And why half? We'll explain shortly below (after explaining the second part).
*
* Stored permits that are beyond halfPermits, are mapped to an ascending line, that goes
* from stableInterval to 3 * stableInterval. The average height for that part is
* 2 * stableInterval, and is sized appropriately to have an area _equal_ to the
* specified warmup period. Thus, by point (4) above, it takes "warmupPeriod" amount of time
* to go from maxPermits to halfPermits.
*
* BUT, by point (3) above, it only takes "warmupPeriod / 2" amount of time to return back
* to maxPermits, from halfPermits! (Because the trapezoid has double the area of the rectangle
* of height stableInterval and equivalent width). We decided that the "cooldown period"
* time should be equivalent to "warmup period", thus a fully saturated RateLimiter
* (with zero stored permits, serving only fresh ones) can go to a fully unsaturated
* (with storedPermits == maxPermits) in the same amount of time it takes for a fully
* unsaturated RateLimiter to return to the stableInterval -- which happens in halfPermits,
* since beyond that point, we use a horizontal line of "stableInterval" height, simulating
* the regular rate.
*
* Thus, we have figured all dimensions of this shape, to give all the desired
* properties:
* - the width is warmupPeriod / stableInterval, to make cooldownPeriod == warmupPeriod
* - the slope starts at the middle, and goes from stableInterval to 3*stableInterval so
* to have halfPermits being spend in double the usual time (half the rate), while their
* respective rate is steadily ramping up
*/
private static class WarmingUp extends RateLimiter {
final long warmupPeriodMicros;
/**
* The slope of the line from the stable interval (when permits == 0), to the cold interval
* (when permits == maxPermits)
*/
private double slope;
private double halfPermits;
WarmingUp(SleepingTicker ticker, long warmupPeriod, TimeUnit timeUnit) {
super(ticker);
this.warmupPeriodMicros = timeUnit.toMicros(warmupPeriod);
}
@Override
void doSetRate(double permitsPerSecond, double stableIntervalMicros) {
double oldMaxPermits = maxPermits;
maxPermits = warmupPeriodMicros / stableIntervalMicros;
halfPermits = maxPermits / 2.0;
// Stable interval is x, cold is 3x, so on average it's 2x. Double the time -> halve the rate
double coldIntervalMicros = stableIntervalMicros * 3.0;
slope = (coldIntervalMicros - stableIntervalMicros) / halfPermits;
if (oldMaxPermits == Double.POSITIVE_INFINITY) {
// if we don't special-case this, we would get storedPermits == NaN, below
storedPermits = 0.0;
} else {
storedPermits = (oldMaxPermits == 0.0)
? maxPermits // initial state is cold
: storedPermits * maxPermits / oldMaxPermits;
}
}
@Override
long storedPermitsToWaitTime(double storedPermits, double permitsToTake) {
double availablePermitsAboveHalf = storedPermits - halfPermits;
long micros = 0;
// measuring the integral on the right part of the function (the climbing line)
if (availablePermitsAboveHalf > 0.0) {
double permitsAboveHalfToTake = Math.min(availablePermitsAboveHalf, permitsToTake);
micros = (long) (permitsAboveHalfToTake * (permitsToTime(availablePermitsAboveHalf)
+ permitsToTime(availablePermitsAboveHalf - permitsAboveHalfToTake)) / 2.0);
permitsToTake -= permitsAboveHalfToTake;
}
// measuring the integral on the left part of the function (the horizontal line)
micros += (stableIntervalMicros * permitsToTake);
return micros;
}
private double permitsToTime(double permits) {
return stableIntervalMicros + permits * slope;
}
}
/**
* This implements a trivial function, where storedPermits are translated to
* zero throttling - thus, a client gets an infinite speedup for permits acquired out
* of the storedPermits pool. This is also used for the special case of the "metronome",
* where the width of the function is also zero; maxStoredPermits is zero, thus
* storedPermits and permitsToTake are always zero as well. Such a RateLimiter can
* not save permits when unused, thus all permits it serves are fresh, using the
* designated rate.
*/
private static class Bursty extends RateLimiter {
Bursty(SleepingTicker ticker) {
super(ticker);
}
@Override
void doSetRate(double permitsPerSecond, double stableIntervalMicros) {
double oldMaxPermits = this.maxPermits;
/*
* We allow the equivalent work of up to one second to be granted with zero waiting, if the
* rate limiter has been unused for as much. This is to avoid potentially producing tiny
* wait interval between subsequent requests for sufficiently large rates, which would
* unnecessarily overconstrain the thread scheduler.
*/
maxPermits = permitsPerSecond; // one second worth of permits
storedPermits = (oldMaxPermits == 0.0)
? 0.0 // initial state
: storedPermits * maxPermits / oldMaxPermits;
}
@Override
long storedPermitsToWaitTime(double storedPermits, double permitsToTake) {
return 0L;
}
}
@VisibleForTesting
static abstract class SleepingTicker extends Ticker {
abstract void sleepMicrosUninterruptibly(long micros);
static final SleepingTicker SYSTEM_TICKER = new SleepingTicker() {
@Override
public long read() {
return systemTicker().read();
}
@Override
public void sleepMicrosUninterruptibly(long micros) {
if (micros > 0) {
Uninterruptibles.sleepUninterruptibly(micros, TimeUnit.MICROSECONDS);
}
}
};
}
}
| Java |
/*
* Written by Doug Lea and Martin Buchholz with assistance from
* members of JCP JSR-166 Expert Group and released to the public
* domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDouble.java?revision=1.13
* (Modified to adapt to guava coding conventions and
* to use AtomicLongFieldUpdater instead of sun.misc.Unsafe)
*/
package com.google.common.util.concurrent;
import static java.lang.Double.doubleToRawLongBits;
import static java.lang.Double.longBitsToDouble;
import com.google.common.annotations.Beta;
import java.util.concurrent.atomic.AtomicLongFieldUpdater;
/**
* A {@code double} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An {@code
* AtomicDouble} is used in applications such as atomic accumulation,
* and cannot be used as a replacement for a {@link Double}. However,
* this class does extend {@code Number} to allow uniform access by
* tools and utilities that deal with numerically-based classes.
*
* <p><a name="bitEquals">This class compares primitive {@code double}
* values in methods such as {@link #compareAndSet} by comparing their
* bitwise representation using {@link Double#doubleToRawLongBits},
* which differs from both the primitive double {@code ==} operator
* and from {@link Double#equals}, as if implemented by:
* <pre> {@code
* static boolean bitEquals(double x, double y) {
* long xBits = Double.doubleToRawLongBits(x);
* long yBits = Double.doubleToRawLongBits(y);
* return xBits == yBits;
* }}</pre>
*
* <p>It is possible to write a more scalable updater, at the cost of
* giving up strict atomicity. See for example
* <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleAdder.html"
* DoubleAdder>
* and
* <a href="http://gee.cs.oswego.edu/dl/jsr166/dist/jsr166edocs/jsr166e/DoubleMaxUpdater.html"
* DoubleMaxUpdater>.
*
* @author Doug Lea
* @author Martin Buchholz
* @since 11.0
*/
@Beta
public class AtomicDouble extends Number implements java.io.Serializable {
private static final long serialVersionUID = 0L;
private transient volatile long value;
private static final AtomicLongFieldUpdater<AtomicDouble> updater =
AtomicLongFieldUpdater.newUpdater(AtomicDouble.class, "value");
/**
* Creates a new {@code AtomicDouble} with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicDouble(double initialValue) {
value = doubleToRawLongBits(initialValue);
}
/**
* Creates a new {@code AtomicDouble} with initial value {@code 0.0}.
*/
public AtomicDouble() {
// assert doubleToRawLongBits(0.0) == 0L;
}
/**
* Gets the current value.
*
* @return the current value
*/
public final double get() {
return longBitsToDouble(value);
}
/**
* Sets to the given value.
*
* @param newValue the new value
*/
public final void set(double newValue) {
long next = doubleToRawLongBits(newValue);
value = next;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
*/
public final void lazySet(double newValue) {
set(newValue);
// TODO(user): replace with code below when jdk5 support is dropped.
// long next = doubleToRawLongBits(newValue);
// updater.lazySet(this, next);
}
/**
* Atomically sets to the given value and returns the old value.
*
* @param newValue the new value
* @return the previous value
*/
public final double getAndSet(double newValue) {
long next = doubleToRawLongBits(newValue);
return longBitsToDouble(updater.getAndSet(this, next));
}
/**
* Atomically sets the value to the given updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful. False return indicates that
* the actual value was not bitwise equal to the expected value.
*/
public final boolean compareAndSet(double expect, double update) {
return updater.compareAndSet(this,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically sets the value to the given updated value
* if the current value is <a href="#bitEquals">bitwise equal</a>
* to the expected value.
*
* <p>May <a
* href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious">
* fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return {@code true} if successful
*/
public final boolean weakCompareAndSet(double expect, double update) {
return updater.weakCompareAndSet(this,
doubleToRawLongBits(expect),
doubleToRawLongBits(update));
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the previous value
*/
public final double getAndAdd(double delta) {
while (true) {
long current = value;
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (updater.compareAndSet(this, current, next)) {
return currentVal;
}
}
}
/**
* Atomically adds the given value to the current value.
*
* @param delta the value to add
* @return the updated value
*/
public final double addAndGet(double delta) {
while (true) {
long current = value;
double currentVal = longBitsToDouble(current);
double nextVal = currentVal + delta;
long next = doubleToRawLongBits(nextVal);
if (updater.compareAndSet(this, current, next)) {
return nextVal;
}
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value
*/
public String toString() {
return Double.toString(get());
}
/**
* Returns the value of this {@code AtomicDouble} as an {@code int}
* after a narrowing primitive conversion.
*/
public int intValue() {
return (int) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code long}
* after a narrowing primitive conversion.
*/
public long longValue() {
return (long) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code float}
* after a narrowing primitive conversion.
*/
public float floatValue() {
return (float) get();
}
/**
* Returns the value of this {@code AtomicDouble} as a {@code double}.
*/
public double doubleValue() {
return get();
}
/**
* Saves the state to a stream (that is, serializes it).
*
* @serialData The current value is emitted (a {@code double}).
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
s.defaultWriteObject();
s.writeDouble(get());
}
/**
* Reconstitutes the instance from a stream (that is, deserializes it).
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
s.defaultReadObject();
set(s.readDouble());
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.collect.ObjectArrays;
import com.google.common.collect.Sets;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A TimeLimiter that runs method calls in the background using an
* {@link ExecutorService}. If the time limit expires for a given method call,
* the thread running the call will be interrupted.
*
* @author Kevin Bourrillion
* @since 1.0
*/
@Beta
public final class SimpleTimeLimiter implements TimeLimiter {
private final ExecutorService executor;
/**
* Constructs a TimeLimiter instance using the given executor service to
* execute proxied method calls.
* <p>
* <b>Warning:</b> using a bounded executor
* may be counterproductive! If the thread pool fills up, any time callers
* spend waiting for a thread may count toward their time limit, and in
* this case the call may even time out before the target method is ever
* invoked.
*
* @param executor the ExecutorService that will execute the method calls on
* the target objects; for example, a {@link
* Executors#newCachedThreadPool()}.
*/
public SimpleTimeLimiter(ExecutorService executor) {
this.executor = checkNotNull(executor);
}
/**
* Constructs a TimeLimiter instance using a {@link
* Executors#newCachedThreadPool()} to execute proxied method calls.
*
* <p><b>Warning:</b> using a bounded executor may be counterproductive! If
* the thread pool fills up, any time callers spend waiting for a thread may
* count toward their time limit, and in this case the call may even time out
* before the target method is ever invoked.
*/
public SimpleTimeLimiter() {
this(Executors.newCachedThreadPool());
}
@Override
public <T> T newProxy(final T target, Class<T> interfaceType,
final long timeoutDuration, final TimeUnit timeoutUnit) {
checkNotNull(target);
checkNotNull(interfaceType);
checkNotNull(timeoutUnit);
checkArgument(timeoutDuration > 0, "bad timeout: " + timeoutDuration);
checkArgument(interfaceType.isInterface(),
"interfaceType must be an interface type");
final Set<Method> interruptibleMethods
= findInterruptibleMethods(interfaceType);
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object obj, final Method method, final Object[] args)
throws Throwable {
Callable<Object> callable = new Callable<Object>() {
@Override
public Object call() throws Exception {
try {
return method.invoke(target, args);
} catch (InvocationTargetException e) {
throwCause(e, false);
throw new AssertionError("can't get here");
}
}
};
return callWithTimeout(callable, timeoutDuration, timeoutUnit,
interruptibleMethods.contains(method));
}
};
return newProxy(interfaceType, handler);
}
// TODO: should this actually throw only ExecutionException?
@Override
public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration,
TimeUnit timeoutUnit, boolean amInterruptible) throws Exception {
checkNotNull(callable);
checkNotNull(timeoutUnit);
checkArgument(timeoutDuration > 0, "timeout must be positive: %s",
timeoutDuration);
Future<T> future = executor.submit(callable);
try {
if (amInterruptible) {
try {
return future.get(timeoutDuration, timeoutUnit);
} catch (InterruptedException e) {
future.cancel(true);
throw e;
}
} else {
return Uninterruptibles.getUninterruptibly(future,
timeoutDuration, timeoutUnit);
}
} catch (ExecutionException e) {
throw throwCause(e, true);
} catch (TimeoutException e) {
future.cancel(true);
throw new UncheckedTimeoutException(e);
}
}
private static Exception throwCause(Exception e, boolean combineStackTraces)
throws Exception {
Throwable cause = e.getCause();
if (cause == null) {
throw e;
}
if (combineStackTraces) {
StackTraceElement[] combined = ObjectArrays.concat(cause.getStackTrace(),
e.getStackTrace(), StackTraceElement.class);
cause.setStackTrace(combined);
}
if (cause instanceof Exception) {
throw (Exception) cause;
}
if (cause instanceof Error) {
throw (Error) cause;
}
// The cause is a weird kind of Throwable, so throw the outer exception.
throw e;
}
private static Set<Method> findInterruptibleMethods(Class<?> interfaceType) {
Set<Method> set = Sets.newHashSet();
for (Method m : interfaceType.getMethods()) {
if (declaresInterruptedEx(m)) {
set.add(m);
}
}
return set;
}
private static boolean declaresInterruptedEx(Method method) {
for (Class<?> exType : method.getExceptionTypes()) {
// debate: == or isAssignableFrom?
if (exType == InterruptedException.class) {
return true;
}
}
return false;
}
// TODO: replace with version in common.reflect if and when it's open-sourced
private static <T> T newProxy(
Class<T> interfaceType, InvocationHandler handler) {
Object object = Proxy.newProxyInstance(interfaceType.getClassLoader(),
new Class<?>[] { interfaceType }, handler);
return interfaceType.cast(object);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import java.util.concurrent.Callable;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to the {@link Callable} interface.
*
* @author Isaac Shum
* @since 1.0
*/
public final class Callables {
private Callables() {}
/**
* Creates a {@code Callable} which immediately returns a preset value each
* time it is called.
*/
public static <T> Callable<T> returning(final @Nullable T value) {
return new Callable<T>() {
@Override public T call() {
return value;
}
};
}
}
| Java |
/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor;
import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly;
import static java.lang.Thread.currentThread;
import static java.util.Arrays.asList;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;
import com.google.common.collect.Sets;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to the {@link Future} interface.
*
* <p>Many of these methods use the {@link ListenableFuture} API; consult the
* Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained">
* {@code ListenableFuture}</a>.
*
* @author Kevin Bourrillion
* @author Nishant Thakkar
* @author Sven Mawson
* @since 1.0
*/
@Beta
public final class Futures {
private Futures() {}
/**
* Creates a {@link CheckedFuture} out of a normal {@link ListenableFuture}
* and a {@link Function} that maps from {@link Exception} instances into the
* appropriate checked type.
*
* <p>The given mapping function will be applied to an
* {@link InterruptedException}, a {@link CancellationException}, or an
* {@link ExecutionException}.
* See {@link Future#get()} for details on the exceptions thrown.
*
* @since 9.0 (source-compatible since 1.0)
*/
public static <V, X extends Exception> CheckedFuture<V, X> makeChecked(
ListenableFuture<V> future, Function<Exception, X> mapper) {
return new MappingCheckedFuture<V, X>(checkNotNull(future), mapper);
}
private abstract static class ImmediateFuture<V>
implements ListenableFuture<V> {
private static final Logger log =
Logger.getLogger(ImmediateFuture.class.getName());
@Override
public void addListener(Runnable listener, Executor executor) {
checkNotNull(listener, "Runnable was null.");
checkNotNull(executor, "Executor was null.");
try {
executor.execute(listener);
} catch (RuntimeException e) {
// ListenableFuture's contract is that it will not throw unchecked
// exceptions, so log the bad runnable and/or executor and swallow it.
log.log(Level.SEVERE, "RuntimeException while executing runnable "
+ listener + " with executor " + executor, e);
}
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
@Override
public abstract V get() throws ExecutionException;
@Override
public V get(long timeout, TimeUnit unit) throws ExecutionException {
return get();
}
@Override
public boolean isCancelled() {
return false;
}
@Override
public boolean isDone() {
return true;
}
}
private static class ImmediateSuccessfulFuture<V> extends ImmediateFuture<V> {
@Nullable private final V value;
ImmediateSuccessfulFuture(@Nullable V value) {
this.value = value;
}
@Override
public V get() {
return value;
}
}
private static class ImmediateSuccessfulCheckedFuture<V, X extends Exception>
extends ImmediateFuture<V> implements CheckedFuture<V, X> {
@Nullable private final V value;
ImmediateSuccessfulCheckedFuture(@Nullable V value) {
this.value = value;
}
@Override
public V get() {
return value;
}
@Override
public V checkedGet() {
return value;
}
@Override
public V checkedGet(long timeout, TimeUnit unit) {
return value;
}
}
private static class ImmediateFailedFuture<V> extends ImmediateFuture<V> {
private final Throwable thrown;
ImmediateFailedFuture(Throwable thrown) {
this.thrown = thrown;
}
@Override
public V get() throws ExecutionException {
throw new ExecutionException(thrown);
}
}
private static class ImmediateCancelledFuture<V> extends ImmediateFuture<V> {
private final CancellationException thrown;
ImmediateCancelledFuture() {
this.thrown = new CancellationException("Immediate cancelled future.");
}
@Override
public boolean isCancelled() {
return true;
}
@Override
public V get() {
throw AbstractFuture.cancellationExceptionWithCause(
"Task was cancelled.", thrown);
}
}
private static class ImmediateFailedCheckedFuture<V, X extends Exception>
extends ImmediateFuture<V> implements CheckedFuture<V, X> {
private final X thrown;
ImmediateFailedCheckedFuture(X thrown) {
this.thrown = thrown;
}
@Override
public V get() throws ExecutionException {
throw new ExecutionException(thrown);
}
@Override
public V checkedGet() throws X {
throw thrown;
}
@Override
public V checkedGet(long timeout, TimeUnit unit) throws X {
throw thrown;
}
}
/**
* Creates a {@code ListenableFuture} which has its value set immediately upon
* construction. The getters just return the value. This {@code Future} can't
* be canceled or timed out and its {@code isDone()} method always returns
* {@code true}.
*/
public static <V> ListenableFuture<V> immediateFuture(@Nullable V value) {
return new ImmediateSuccessfulFuture<V>(value);
}
/**
* Returns a {@code CheckedFuture} which has its value set immediately upon
* construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} or {@code
* checkedGet()} will immediately return the provided value.
*/
public static <V, X extends Exception> CheckedFuture<V, X>
immediateCheckedFuture(@Nullable V value) {
return new ImmediateSuccessfulCheckedFuture<V, X>(value);
}
/**
* Returns a {@code ListenableFuture} which has an exception set immediately
* upon construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} will immediately
* throw the provided {@code Throwable} wrapped in an {@code
* ExecutionException}.
*/
public static <V> ListenableFuture<V> immediateFailedFuture(
Throwable throwable) {
checkNotNull(throwable);
return new ImmediateFailedFuture<V>(throwable);
}
/**
* Creates a {@code ListenableFuture} which is cancelled immediately upon
* construction, so that {@code isCancelled()} always returns {@code true}.
*
* @since 14.0
*/
public static <V> ListenableFuture<V> immediateCancelledFuture() {
return new ImmediateCancelledFuture<V>();
}
/**
* Returns a {@code CheckedFuture} which has an exception set immediately upon
* construction.
*
* <p>The returned {@code Future} can't be cancelled, and its {@code isDone()}
* method always returns {@code true}. Calling {@code get()} will immediately
* throw the provided {@code Exception} wrapped in an {@code
* ExecutionException}, and calling {@code checkedGet()} will throw the
* provided exception itself.
*/
public static <V, X extends Exception> CheckedFuture<V, X>
immediateFailedCheckedFuture(X exception) {
checkNotNull(exception);
return new ImmediateFailedCheckedFuture<V, X>(exception);
}
/**
* Returns a {@code Future} whose result is taken from the given primary
* {@code input} or, if the primary input fails, from the {@code Future}
* provided by the {@code fallback}. {@link FutureFallback#create} is not
* invoked until the primary input has failed, so if the primary input
* succeeds, it is never invoked. If, during the invocation of {@code
* fallback}, an exception is thrown, this exception is used as the result of
* the output {@code Future}.
*
* <p>Below is an example of a fallback that returns a default value if an
* exception occurs:
*
* <pre> {@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback(
* fetchCounterFuture, new FutureFallback<Integer>() {
* public ListenableFuture<Integer> create(Throwable t) {
* // Returning "0" as the default for the counter when the
* // exception happens.
* return immediateFuture(0);
* }
* });
* }</pre>
*
* The fallback can also choose to propagate the original exception when
* desired:
*
* <pre> {@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter only in case the exception was a
* // TimeoutException.
* ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback(
* fetchCounterFuture, new FutureFallback<Integer>() {
* public ListenableFuture<Integer> create(Throwable t) {
* if (t instanceof TimeoutException) {
* return immediateFuture(0);
* }
* return immediateFailedFuture(t);
* }
* });
* }</pre>
*
* Note: If the derived {@code Future} is slow or heavyweight to create
* (whether the {@code Future} itself is slow or heavyweight to complete is
* irrelevant), consider {@linkplain #withFallback(ListenableFuture,
* FutureFallback, Executor) supplying an executor}. If you do not supply an
* executor, {@code withFallback} will use {@link
* MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some
* caveats for heavier operations. For example, the call to {@code
* fallback.create} may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code withFallback}
* is called, {@code withFallback} will call {@code fallback.create} inline.
* <li>If the input {@code Future} is not yet done, {@code withFallback} will
* schedule {@code fallback.create} to be run by the thread that completes
* the input {@code Future}, which may be an internal system thread such as
* an RPC network thread.
* </ul>
*
* Also note that, regardless of which thread executes {@code
* fallback.create}, all other registered but unexecuted listeners are
* prevented from running during its execution, even if those listeners are
* to run in other executors.
*
* @param input the primary input {@code Future}
* @param fallback the {@link FutureFallback} implementation to be called if
* {@code input} fails
*/
public static <V> ListenableFuture<V> withFallback(
ListenableFuture<? extends V> input,
FutureFallback<? extends V> fallback) {
return withFallback(input, fallback, sameThreadExecutor());
}
/**
* Returns a {@code Future} whose result is taken from the given primary
* {@code input} or, if the primary input fails, from the {@code Future}
* provided by the {@code fallback}. {@link FutureFallback#create} is not
* invoked until the primary input has failed, so if the primary input
* succeeds, it is never invoked. If, during the invocation of {@code
* fallback}, an exception is thrown, this exception is used as the result of
* the output {@code Future}.
*
* <p>Below is an example of a fallback that returns a default value if an
* exception occurs:
*
* <pre> {@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter in case an exception happens when
* // processing the RPC to fetch counters.
* ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback(
* fetchCounterFuture, new FutureFallback<Integer>() {
* public ListenableFuture<Integer> create(Throwable t) {
* // Returning "0" as the default for the counter when the
* // exception happens.
* return immediateFuture(0);
* }
* }, sameThreadExecutor());
* }</pre>
*
* The fallback can also choose to propagate the original exception when
* desired:
*
* <pre> {@code
* ListenableFuture<Integer> fetchCounterFuture = ...;
*
* // Falling back to a zero counter only in case the exception was a
* // TimeoutException.
* ListenableFuture<Integer> faultTolerantFuture = Futures.withFallback(
* fetchCounterFuture, new FutureFallback<Integer>() {
* public ListenableFuture<Integer> create(Throwable t) {
* if (t instanceof TimeoutException) {
* return immediateFuture(0);
* }
* return immediateFailedFuture(t);
* }
* }, sameThreadExecutor());
* }</pre>
*
* When the execution of {@code fallback.create} is fast and lightweight
* (though the {@code Future} it returns need not meet these criteria),
* consider {@linkplain #withFallback(ListenableFuture, FutureFallback)
* omitting the executor} or explicitly specifying {@code
* sameThreadExecutor}. However, be aware of the caveats documented in the
* link above.
*
* @param input the primary input {@code Future}
* @param fallback the {@link FutureFallback} implementation to be called if
* {@code input} fails
* @param executor the executor that runs {@code fallback} if {@code input}
* fails
*/
public static <V> ListenableFuture<V> withFallback(
ListenableFuture<? extends V> input,
FutureFallback<? extends V> fallback, Executor executor) {
checkNotNull(fallback);
return new FallbackFuture<V>(input, fallback, executor);
}
/**
* A future that falls back on a second, generated future, in case its
* original future fails.
*/
private static class FallbackFuture<V> extends AbstractFuture<V> {
private volatile ListenableFuture<? extends V> running;
FallbackFuture(ListenableFuture<? extends V> input,
final FutureFallback<? extends V> fallback,
final Executor executor) {
running = input;
addCallback(running, new FutureCallback<V>() {
@Override
public void onSuccess(V value) {
set(value);
}
@Override
public void onFailure(Throwable t) {
if (isCancelled()) {
return;
}
try {
running = fallback.create(t);
if (isCancelled()) { // in case cancel called in the meantime
running.cancel(wasInterrupted());
return;
}
addCallback(running, new FutureCallback<V>() {
@Override
public void onSuccess(V value) {
set(value);
}
@Override
public void onFailure(Throwable t) {
if (running.isCancelled()) {
cancel(false);
} else {
setException(t);
}
}
}, sameThreadExecutor());
} catch (Exception e) {
setException(e);
} catch (Error e) {
setException(e); // note: rethrows
}
}
}, executor);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
if (super.cancel(mayInterruptIfRunning)) {
running.cancel(mayInterruptIfRunning);
return true;
}
return false;
}
}
/**
* Returns a new {@code ListenableFuture} whose result is asynchronously
* derived from the result of the given {@code Future}. More precisely, the
* returned {@code Future} takes its result from a {@code Future} produced by
* applying the given {@code AsyncFunction} to the result of the original
* {@code Future}. Example:
*
* <pre> {@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* AsyncFunction<RowKey, QueryResult> queryFunction =
* new AsyncFunction<RowKey, QueryResult>() {
* public ListenableFuture<QueryResult> apply(RowKey rowKey) {
* return dataService.read(rowKey);
* }
* };
* ListenableFuture<QueryResult> queryFuture =
* transform(rowKeyFuture, queryFunction);
* }</pre>
*
* Note: If the derived {@code Future} is slow or heavyweight to create
* (whether the {@code Future} itself is slow or heavyweight to complete is
* irrelevant), consider {@linkplain #transform(ListenableFuture,
* AsyncFunction, Executor) supplying an executor}. If you do not supply an
* executor, {@code transform} will use {@link
* MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some
* caveats for heavier operations. For example, the call to {@code
* function.apply} may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code transform} is
* called, {@code transform} will call {@code function.apply} inline.
* <li>If the input {@code Future} is not yet done, {@code transform} will
* schedule {@code function.apply} to be run by the thread that completes the
* input {@code Future}, which may be an internal system thread such as an
* RPC network thread.
* </ul>
*
* Also note that, regardless of which thread executes {@code
* function.apply}, all other registered but unexecuted listeners are
* prevented from running during its execution, even if those listeners are
* to run in other executors.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future and that of the future returned by the
* function. That is, if the returned {@code Future} is cancelled, it will
* attempt to cancel the other two, and if either of the other two is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* @param input The future to transform
* @param function A function to transform the result of the input future
* to the result of the output future
* @return A future that holds result of the function (if the input succeeded)
* or the original input's failure (if not)
* @since 11.0
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
AsyncFunction<? super I, ? extends O> function) {
return transform(input, function, MoreExecutors.sameThreadExecutor());
}
/**
* Returns a new {@code ListenableFuture} whose result is asynchronously
* derived from the result of the given {@code Future}. More precisely, the
* returned {@code Future} takes its result from a {@code Future} produced by
* applying the given {@code AsyncFunction} to the result of the original
* {@code Future}. Example:
*
* <pre> {@code
* ListenableFuture<RowKey> rowKeyFuture = indexService.lookUp(query);
* AsyncFunction<RowKey, QueryResult> queryFunction =
* new AsyncFunction<RowKey, QueryResult>() {
* public ListenableFuture<QueryResult> apply(RowKey rowKey) {
* return dataService.read(rowKey);
* }
* };
* ListenableFuture<QueryResult> queryFuture =
* transform(rowKeyFuture, queryFunction, executor);
* }</pre>
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future and that of the future returned by the
* chain function. That is, if the returned {@code Future} is cancelled, it
* will attempt to cancel the other two, and if either of the other two is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>When the execution of {@code function.apply} is fast and lightweight
* (though the {@code Future} it returns need not meet these criteria),
* consider {@linkplain #transform(ListenableFuture, AsyncFunction) omitting
* the executor} or explicitly specifying {@code sameThreadExecutor}.
* However, be aware of the caveats documented in the link above.
*
* @param input The future to transform
* @param function A function to transform the result of the input future
* to the result of the output future
* @param executor Executor to run the function in.
* @return A future that holds result of the function (if the input succeeded)
* or the original input's failure (if not)
* @since 11.0
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
AsyncFunction<? super I, ? extends O> function,
Executor executor) {
ChainingListenableFuture<I, O> output =
new ChainingListenableFuture<I, O>(function, input);
input.addListener(output, executor);
return output;
}
/**
* Returns a new {@code ListenableFuture} whose result is the product of
* applying the given {@code Function} to the result of the given {@code
* Future}. Example:
*
* <pre> {@code
* ListenableFuture<QueryResult> queryFuture = ...;
* Function<QueryResult, List<Row>> rowsFunction =
* new Function<QueryResult, List<Row>>() {
* public List<Row> apply(QueryResult queryResult) {
* return queryResult.getRows();
* }
* };
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, rowsFunction);
* }</pre>
*
* Note: If the transformation is slow or heavyweight, consider {@linkplain
* #transform(ListenableFuture, Function, Executor) supplying an executor}.
* If you do not supply an executor, {@code transform} will use {@link
* MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries some
* caveats for heavier operations. For example, the call to {@code
* function.apply} may run on an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code transform} is
* called, {@code transform} will call {@code function.apply} inline.
* <li>If the input {@code Future} is not yet done, {@code transform} will
* schedule {@code function.apply} to be run by the thread that completes the
* input {@code Future}, which may be an internal system thread such as an
* RPC network thread.
* </ul>
*
* Also note that, regardless of which thread executes {@code
* function.apply}, all other registered but unexecuted listeners are
* prevented from running during its execution, even if those listeners are
* to run in other executors.
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future. That is, if the returned {@code Future}
* is cancelled, it will attempt to cancel the input, and if the input is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future. This will be run in the thread
* that notifies input it is complete.
* @return A future that holds result of the transformation.
* @since 9.0 (in 1.0 as {@code compose})
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
final Function<? super I, ? extends O> function) {
return transform(input, function, MoreExecutors.sameThreadExecutor());
}
/**
* Returns a new {@code ListenableFuture} whose result is the product of
* applying the given {@code Function} to the result of the given {@code
* Future}. Example:
*
* <pre> {@code
* ListenableFuture<QueryResult> queryFuture = ...;
* Function<QueryResult, List<Row>> rowsFunction =
* new Function<QueryResult, List<Row>>() {
* public List<Row> apply(QueryResult queryResult) {
* return queryResult.getRows();
* }
* };
* ListenableFuture<List<Row>> rowsFuture =
* transform(queryFuture, rowsFunction, executor);
* }</pre>
*
* <p>The returned {@code Future} attempts to keep its cancellation state in
* sync with that of the input future. That is, if the returned {@code Future}
* is cancelled, it will attempt to cancel the input, and if the input is
* cancelled, the returned {@code Future} will receive a callback in which it
* will attempt to cancel itself.
*
* <p>An example use of this method is to convert a serializable object
* returned from an RPC into a POJO.
*
* <p>When the transformation is fast and lightweight, consider {@linkplain
* #transform(ListenableFuture, Function) omitting the executor} or
* explicitly specifying {@code sameThreadExecutor}. However, be aware of the
* caveats documented in the link above.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future.
* @param executor Executor to run the function in.
* @return A future that holds result of the transformation.
* @since 9.0 (in 2.0 as {@code compose})
*/
public static <I, O> ListenableFuture<O> transform(ListenableFuture<I> input,
final Function<? super I, ? extends O> function, Executor executor) {
checkNotNull(function);
AsyncFunction<I, O> wrapperFunction
= new AsyncFunction<I, O>() {
@Override public ListenableFuture<O> apply(I input) {
O output = function.apply(input);
return immediateFuture(output);
}
};
return transform(input, wrapperFunction, executor);
}
/**
* Like {@link #transform(ListenableFuture, Function)} except that the
* transformation {@code function} is invoked on each call to
* {@link Future#get() get()} on the returned future.
*
* <p>The returned {@code Future} reflects the input's cancellation
* state directly, and any attempt to cancel the returned Future is likewise
* passed through to the input Future.
*
* <p>Note that calls to {@linkplain Future#get(long, TimeUnit) timed get}
* only apply the timeout to the execution of the underlying {@code Future},
* <em>not</em> to the execution of the transformation function.
*
* <p>The primary audience of this method is callers of {@code transform}
* who don't have a {@code ListenableFuture} available and
* do not mind repeated, lazy function evaluation.
*
* @param input The future to transform
* @param function A Function to transform the results of the provided future
* to the results of the returned future.
* @return A future that returns the result of the transformation.
* @since 10.0
*/
@Beta
public static <I, O> Future<O> lazyTransform(final Future<I> input,
final Function<? super I, ? extends O> function) {
checkNotNull(input);
checkNotNull(function);
return new Future<O>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return input.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return input.isCancelled();
}
@Override
public boolean isDone() {
return input.isDone();
}
@Override
public O get() throws InterruptedException, ExecutionException {
return applyTransformation(input.get());
}
@Override
public O get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return applyTransformation(input.get(timeout, unit));
}
private O applyTransformation(I input) throws ExecutionException {
try {
return function.apply(input);
} catch (Throwable t) {
throw new ExecutionException(t);
}
}
};
}
/**
* An implementation of {@code ListenableFuture} that also implements
* {@code Runnable} so that it can be used to nest ListenableFutures.
* Once the passed-in {@code ListenableFuture} is complete, it calls the
* passed-in {@code Function} to generate the result.
*
* <p>If the function throws any checked exceptions, they should be wrapped
* in a {@code UndeclaredThrowableException} so that this class can get
* access to the cause.
*/
private static class ChainingListenableFuture<I, O>
extends AbstractFuture<O> implements Runnable {
private AsyncFunction<? super I, ? extends O> function;
private ListenableFuture<? extends I> inputFuture;
private volatile ListenableFuture<? extends O> outputFuture;
private final CountDownLatch outputCreated = new CountDownLatch(1);
private ChainingListenableFuture(
AsyncFunction<? super I, ? extends O> function,
ListenableFuture<? extends I> inputFuture) {
this.function = checkNotNull(function);
this.inputFuture = checkNotNull(inputFuture);
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
/*
* Our additional cancellation work needs to occur even if
* !mayInterruptIfRunning, so we can't move it into interruptTask().
*/
if (super.cancel(mayInterruptIfRunning)) {
// This should never block since only one thread is allowed to cancel
// this Future.
cancel(inputFuture, mayInterruptIfRunning);
cancel(outputFuture, mayInterruptIfRunning);
return true;
}
return false;
}
private void cancel(@Nullable Future<?> future,
boolean mayInterruptIfRunning) {
if (future != null) {
future.cancel(mayInterruptIfRunning);
}
}
@Override
public void run() {
try {
I sourceResult;
try {
sourceResult = getUninterruptibly(inputFuture);
} catch (CancellationException e) {
// Cancel this future and return.
// At this point, inputFuture is cancelled and outputFuture doesn't
// exist, so the value of mayInterruptIfRunning is irrelevant.
cancel(false);
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
return;
}
final ListenableFuture<? extends O> outputFuture = this.outputFuture =
function.apply(sourceResult);
if (isCancelled()) {
outputFuture.cancel(wasInterrupted());
this.outputFuture = null;
return;
}
outputFuture.addListener(new Runnable() {
@Override
public void run() {
try {
// Here it would have been nice to have had an
// UninterruptibleListenableFuture, but we don't want to start a
// combinatorial explosion of interfaces, so we have to make do.
set(getUninterruptibly(outputFuture));
} catch (CancellationException e) {
// Cancel this future and return.
// At this point, inputFuture and outputFuture are done, so the
// value of mayInterruptIfRunning is irrelevant.
cancel(false);
return;
} catch (ExecutionException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} finally {
// Don't pin inputs beyond completion
ChainingListenableFuture.this.outputFuture = null;
}
}
}, MoreExecutors.sameThreadExecutor());
} catch (UndeclaredThrowableException e) {
// Set the cause of the exception as this future's exception
setException(e.getCause());
} catch (Exception e) {
// This exception is irrelevant in this thread, but useful for the
// client
setException(e);
} catch (Error e) {
// Propagate errors up ASAP - our superclass will rethrow the error
setException(e);
} finally {
// Don't pin inputs beyond completion
function = null;
inputFuture = null;
// Allow our get routines to examine outputFuture now.
outputCreated.countDown();
}
}
}
/**
* Returns a new {@code ListenableFuture} whose result is the product of
* calling {@code get()} on the {@code Future} nested within the given {@code
* Future}, effectively chaining the futures one after the other. Example:
*
* <pre> {@code
* SettableFuture<ListenableFuture<String>> nested = SettableFuture.create();
* ListenableFuture<String> dereferenced = dereference(nested);
* }</pre>
*
* <p>This call has the same cancellation and execution semantics as {@link
* #transform(ListenableFuture, AsyncFunction)}, in that the returned {@code
* Future} attempts to keep its cancellation state in sync with both the
* input {@code Future} and the nested {@code Future}. The transformation
* is very lightweight and therefore takes place in the thread that called
* {@code dereference}.
*
* @param nested The nested future to transform.
* @return A future that holds result of the inner future.
* @since 13.0
*/
@Beta
@SuppressWarnings({"rawtypes", "unchecked"})
public static <V> ListenableFuture<V> dereference(
ListenableFuture<? extends ListenableFuture<? extends V>> nested) {
return Futures.transform((ListenableFuture) nested, (AsyncFunction) DEREFERENCER);
}
/**
* Helper {@code Function} for {@link #dereference}.
*/
private static final AsyncFunction<ListenableFuture<Object>, Object> DEREFERENCER =
new AsyncFunction<ListenableFuture<Object>, Object>() {
@Override public ListenableFuture<Object> apply(ListenableFuture<Object> input) {
return input;
}
};
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its input futures, if all succeed. If any input fails, the
* returned future fails.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future will attempt to cancel all the component futures,
* and if any of the provided futures fails or is canceled, this one is,
* too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> allAsList(
ListenableFuture<? extends V>... futures) {
return listFuture(ImmutableList.copyOf(futures), true,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its input futures, if all succeed. If any input fails, the
* returned future fails.
*
* <p>The list of results is in the same order as the input list.
*
* <p>Canceling this future will attempt to cancel all the component futures,
* and if any of the provided futures fails or is canceled, this one is,
* too.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> allAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return listFuture(ImmutableList.copyOf(futures), true,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its successful input futures. The list of results is in the
* same order as the input list, and if any of the provided futures fails or
* is canceled, its corresponding position will contain {@code null} (which is
* indistinguishable from the future having a successful value of
* {@code null}).
*
* <p>Canceling this future will attempt to cancel all the component futures.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(
ListenableFuture<? extends V>... futures) {
return listFuture(ImmutableList.copyOf(futures), false,
MoreExecutors.sameThreadExecutor());
}
/**
* Creates a new {@code ListenableFuture} whose value is a list containing the
* values of all its successful input futures. The list of results is in the
* same order as the input list, and if any of the provided futures fails or
* is canceled, its corresponding position will contain {@code null} (which is
* indistinguishable from the future having a successful value of
* {@code null}).
*
* <p>Canceling this future will attempt to cancel all the component futures.
*
* @param futures futures to combine
* @return a future that provides a list of the results of the component
* futures
* @since 10.0
*/
@Beta
public static <V> ListenableFuture<List<V>> successfulAsList(
Iterable<? extends ListenableFuture<? extends V>> futures) {
return listFuture(ImmutableList.copyOf(futures), false,
MoreExecutors.sameThreadExecutor());
}
/**
* Registers separate success and failure callbacks to be run when the {@code
* Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
* complete} or, if the computation is already complete, immediately.
*
* <p>There is no guaranteed ordering of execution of callbacks, but any
* callback added through this method is guaranteed to be called once the
* computation is complete.
*
* Example: <pre> {@code
* ListenableFuture<QueryResult> future = ...;
* addCallback(future,
* new FutureCallback<QueryResult> {
* public void onSuccess(QueryResult result) {
* storeInCache(result);
* }
* public void onFailure(Throwable t) {
* reportError(t);
* }
* });}</pre>
*
* Note: If the callback is slow or heavyweight, consider {@linkplain
* #addCallback(ListenableFuture, FutureCallback, Executor) supplying an
* executor}. If you do not supply an executor, {@code addCallback} will use
* {@link MoreExecutors#sameThreadExecutor sameThreadExecutor}, which carries
* some caveats for heavier operations. For example, the callback may run on
* an unpredictable or undesirable thread:
*
* <ul>
* <li>If the input {@code Future} is done at the time {@code addCallback} is
* called, {@code addCallback} will execute the callback inline.
* <li>If the input {@code Future} is not yet done, {@code addCallback} will
* schedule the callback to be run by the thread that completes the input
* {@code Future}, which may be an internal system thread such as an RPC
* network thread.
* </ul>
*
* Also note that, regardless of which thread executes the callback, all
* other registered but unexecuted listeners are prevented from running
* during its execution, even if those listeners are to run in other
* executors.
*
* <p>For a more general interface to attach a completion listener to a
* {@code Future}, see {@link ListenableFuture#addListener addListener}.
*
* @param future The future attach the callback to.
* @param callback The callback to invoke when {@code future} is completed.
* @since 10.0
*/
public static <V> void addCallback(ListenableFuture<V> future,
FutureCallback<? super V> callback) {
addCallback(future, callback, MoreExecutors.sameThreadExecutor());
}
/**
* Registers separate success and failure callbacks to be run when the {@code
* Future}'s computation is {@linkplain java.util.concurrent.Future#isDone()
* complete} or, if the computation is already complete, immediately.
*
* <p>The callback is run in {@code executor}.
* There is no guaranteed ordering of execution of callbacks, but any
* callback added through this method is guaranteed to be called once the
* computation is complete.
*
* Example: <pre> {@code
* ListenableFuture<QueryResult> future = ...;
* Executor e = ...
* addCallback(future, e,
* new FutureCallback<QueryResult> {
* public void onSuccess(QueryResult result) {
* storeInCache(result);
* }
* public void onFailure(Throwable t) {
* reportError(t);
* }
* });}</pre>
*
* When the callback is fast and lightweight, consider {@linkplain
* #addCallback(ListenableFuture, FutureCallback) omitting the executor} or
* explicitly specifying {@code sameThreadExecutor}. However, be aware of the
* caveats documented in the link above.
*
* <p>For a more general interface to attach a completion listener to a
* {@code Future}, see {@link ListenableFuture#addListener addListener}.
*
* @param future The future attach the callback to.
* @param callback The callback to invoke when {@code future} is completed.
* @param executor The executor to run {@code callback} when the future
* completes.
* @since 10.0
*/
public static <V> void addCallback(final ListenableFuture<V> future,
final FutureCallback<? super V> callback, Executor executor) {
Preconditions.checkNotNull(callback);
Runnable callbackListener = new Runnable() {
@Override
public void run() {
try {
// TODO(user): (Before Guava release), validate that this
// is the thing for IE.
V value = getUninterruptibly(future);
callback.onSuccess(value);
} catch (ExecutionException e) {
callback.onFailure(e.getCause());
} catch (RuntimeException e) {
callback.onFailure(e);
} catch (Error e) {
callback.onFailure(e);
}
}
};
future.addListener(callbackListener, executor);
}
/**
* Returns the result of {@link Future#get()}, converting most exceptions to a
* new instance of the given checked exception type. This reduces boilerplate
* for a common use of {@code Future} in which it is unnecessary to
* programmatically distinguish between exception types or to extract other
* information from the exception instance.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@code X} if the cause is a checked exception, an {@link
* UncheckedExecutionException} if the cause is a {@code
* RuntimeException}, or an {@link ExecutionError} if the cause is an
* {@code Error}.
* <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
* restoring the interrupt).
* <li>Any {@link CancellationException} is propagated untouched, as is any
* other {@link RuntimeException} (though {@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to continue to treat every checked exception as a
* checked exception, every unchecked exception as an unchecked exception, and
* every error as an error. In addition, the cause of any {@code
* ExecutionException} is wrapped in order to ensure that the new stack trace
* matches that of the current thread.
*
* <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
* public constructor that accepts zero or more arguments, all of type {@code
* String} or {@code Throwable} (preferring constructors with at least one
* {@code String}) and calling the constructor via reflection. If the
* exception did not already have a cause, one is set by calling {@link
* Throwable#initCause(Throwable)} on it. If no such constructor exists, an
* {@code IllegalArgumentException} is thrown.
*
* @throws X if {@code get} throws any checked exception except for an {@code
* ExecutionException} whose cause is not itself a checked exception
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with a {@code RuntimeException} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @throws IllegalArgumentException if {@code exceptionClass} extends {@code
* RuntimeException} or does not have a suitable constructor
* @since 10.0
*/
@Beta
public static <V, X extends Exception> V get(
Future<V> future, Class<X> exceptionClass) throws X {
checkNotNull(future);
checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
"Futures.get exception type (%s) must not be a RuntimeException",
exceptionClass);
try {
return future.get();
} catch (InterruptedException e) {
currentThread().interrupt();
throw newWithCause(exceptionClass, e);
} catch (ExecutionException e) {
wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
throw new AssertionError();
}
}
/**
* Returns the result of {@link Future#get(long, TimeUnit)}, converting most
* exceptions to a new instance of the given checked exception type. This
* reduces boilerplate for a common use of {@code Future} in which it is
* unnecessary to programmatically distinguish between exception types or to
* extract other information from the exception instance.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@code X} if the cause is a checked exception, an {@link
* UncheckedExecutionException} if the cause is a {@code
* RuntimeException}, or an {@link ExecutionError} if the cause is an
* {@code Error}.
* <li>Any {@link InterruptedException} is wrapped in an {@code X} (after
* restoring the interrupt).
* <li>Any {@link TimeoutException} is wrapped in an {@code X}.
* <li>Any {@link CancellationException} is propagated untouched, as is any
* other {@link RuntimeException} (though {@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to continue to treat every checked exception as a
* checked exception, every unchecked exception as an unchecked exception, and
* every error as an error. In addition, the cause of any {@code
* ExecutionException} is wrapped in order to ensure that the new stack trace
* matches that of the current thread.
*
* <p>Instances of {@code exceptionClass} are created by choosing an arbitrary
* public constructor that accepts zero or more arguments, all of type {@code
* String} or {@code Throwable} (preferring constructors with at least one
* {@code String}) and calling the constructor via reflection. If the
* exception did not already have a cause, one is set by calling {@link
* Throwable#initCause(Throwable)} on it. If no such constructor exists, an
* {@code IllegalArgumentException} is thrown.
*
* @throws X if {@code get} throws any checked exception except for an {@code
* ExecutionException} whose cause is not itself a checked exception
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with a {@code RuntimeException} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @throws IllegalArgumentException if {@code exceptionClass} extends {@code
* RuntimeException} or does not have a suitable constructor
* @since 10.0
*/
@Beta
public static <V, X extends Exception> V get(
Future<V> future, long timeout, TimeUnit unit, Class<X> exceptionClass)
throws X {
checkNotNull(future);
checkNotNull(unit);
checkArgument(!RuntimeException.class.isAssignableFrom(exceptionClass),
"Futures.get exception type (%s) must not be a RuntimeException",
exceptionClass);
try {
return future.get(timeout, unit);
} catch (InterruptedException e) {
currentThread().interrupt();
throw newWithCause(exceptionClass, e);
} catch (TimeoutException e) {
throw newWithCause(exceptionClass, e);
} catch (ExecutionException e) {
wrapAndThrowExceptionOrError(e.getCause(), exceptionClass);
throw new AssertionError();
}
}
private static <X extends Exception> void wrapAndThrowExceptionOrError(
Throwable cause, Class<X> exceptionClass) throws X {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
}
if (cause instanceof RuntimeException) {
throw new UncheckedExecutionException(cause);
}
throw newWithCause(exceptionClass, cause);
}
/**
* Returns the result of calling {@link Future#get()} uninterruptibly on a
* task known not to throw a checked exception. This makes {@code Future} more
* suitable for lightweight, fast-running tasks that, barring bugs in the
* code, will not fail. This gives it exception-handling behavior similar to
* that of {@code ForkJoinTask.join}.
*
* <p>Exceptions from {@code Future.get} are treated as follows:
* <ul>
* <li>Any {@link ExecutionException} has its <i>cause</i> wrapped in an
* {@link UncheckedExecutionException} (if the cause is an {@code
* Exception}) or {@link ExecutionError} (if the cause is an {@code
* Error}).
* <li>Any {@link InterruptedException} causes a retry of the {@code get}
* call. The interrupt is restored before {@code getUnchecked} returns.
* <li>Any {@link CancellationException} is propagated untouched. So is any
* other {@link RuntimeException} ({@code get} implementations are
* discouraged from throwing such exceptions).
* </ul>
*
* The overall principle is to eliminate all checked exceptions: to loop to
* avoid {@code InterruptedException}, to pass through {@code
* CancellationException}, and to wrap any exception from the underlying
* computation in an {@code UncheckedExecutionException} or {@code
* ExecutionError}.
*
* <p>For an uninterruptible {@code get} that preserves other exceptions, see
* {@link Uninterruptibles#getUninterruptibly(Future)}.
*
* @throws UncheckedExecutionException if {@code get} throws an {@code
* ExecutionException} with an {@code Exception} as its cause
* @throws ExecutionError if {@code get} throws an {@code ExecutionException}
* with an {@code Error} as its cause
* @throws CancellationException if {@code get} throws a {@code
* CancellationException}
* @since 10.0
*/
@Beta
public static <V> V getUnchecked(Future<V> future) {
checkNotNull(future);
try {
return getUninterruptibly(future);
} catch (ExecutionException e) {
wrapAndThrowUnchecked(e.getCause());
throw new AssertionError();
}
}
private static void wrapAndThrowUnchecked(Throwable cause) {
if (cause instanceof Error) {
throw new ExecutionError((Error) cause);
}
/*
* It's a non-Error, non-Exception Throwable. From my survey of such
* classes, I believe that most users intended to extend Exception, so we'll
* treat it like an Exception.
*/
throw new UncheckedExecutionException(cause);
}
/*
* TODO(user): FutureChecker interface for these to be static methods on? If
* so, refer to it in the (static-method) Futures.get documentation
*/
/*
* Arguably we don't need a timed getUnchecked because any operation slow
* enough to require a timeout is heavyweight enough to throw a checked
* exception and therefore be inappropriate to use with getUnchecked. Further,
* it's not clear that converting the checked TimeoutException to a
* RuntimeException -- especially to an UncheckedExecutionException, since it
* wasn't thrown by the computation -- makes sense, and if we don't convert
* it, the user still has to write a try-catch block.
*
* If you think you would use this method, let us know.
*/
private static <X extends Exception> X newWithCause(
Class<X> exceptionClass, Throwable cause) {
// getConstructors() guarantees this as long as we don't modify the array.
@SuppressWarnings("unchecked")
List<Constructor<X>> constructors =
(List) Arrays.asList(exceptionClass.getConstructors());
for (Constructor<X> constructor : preferringStrings(constructors)) {
@Nullable X instance = newFromConstructor(constructor, cause);
if (instance != null) {
if (instance.getCause() == null) {
instance.initCause(cause);
}
return instance;
}
}
throw new IllegalArgumentException(
"No appropriate constructor for exception of type " + exceptionClass
+ " in response to chained exception", cause);
}
private static <X extends Exception> List<Constructor<X>>
preferringStrings(List<Constructor<X>> constructors) {
return WITH_STRING_PARAM_FIRST.sortedCopy(constructors);
}
private static final Ordering<Constructor<?>> WITH_STRING_PARAM_FIRST =
Ordering.natural().onResultOf(new Function<Constructor<?>, Boolean>() {
@Override public Boolean apply(Constructor<?> input) {
return asList(input.getParameterTypes()).contains(String.class);
}
}).reverse();
@Nullable private static <X> X newFromConstructor(
Constructor<X> constructor, Throwable cause) {
Class<?>[] paramTypes = constructor.getParameterTypes();
Object[] params = new Object[paramTypes.length];
for (int i = 0; i < paramTypes.length; i++) {
Class<?> paramType = paramTypes[i];
if (paramType.equals(String.class)) {
params[i] = cause.toString();
} else if (paramType.equals(Throwable.class)) {
params[i] = cause;
} else {
return null;
}
}
try {
return constructor.newInstance(params);
} catch (IllegalArgumentException e) {
return null;
} catch (InstantiationException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
}
}
private interface FutureCombiner<V, C> {
C combine(List<Optional<V>> values);
}
private static class CombinedFuture<V, C> extends AbstractFuture<C> {
ImmutableCollection<? extends ListenableFuture<? extends V>> futures;
final boolean allMustSucceed;
final AtomicInteger remaining;
FutureCombiner<V, C> combiner;
List<Optional<V>> values;
CombinedFuture(
ImmutableCollection<? extends ListenableFuture<? extends V>> futures,
boolean allMustSucceed, Executor listenerExecutor,
FutureCombiner<V, C> combiner) {
this.futures = futures;
this.allMustSucceed = allMustSucceed;
this.remaining = new AtomicInteger(futures.size());
this.combiner = combiner;
this.values = Lists.newArrayListWithCapacity(futures.size());
init(listenerExecutor);
}
/**
* Must be called at the end of the constructor.
*/
protected void init(final Executor listenerExecutor) {
// First, schedule cleanup to execute when the Future is done.
addListener(new Runnable() {
@Override
public void run() {
// Cancel all the component futures.
if (CombinedFuture.this.isCancelled()) {
for (ListenableFuture<?> future : CombinedFuture.this.futures) {
future.cancel(CombinedFuture.this.wasInterrupted());
}
}
// By now the values array has either been set as the Future's value,
// or (in case of failure) is no longer useful.
CombinedFuture.this.futures = null;
// Let go of the memory held by other futures
CombinedFuture.this.values = null;
// The combiner may also hold state, so free that as well
CombinedFuture.this.combiner = null;
}
}, MoreExecutors.sameThreadExecutor());
// Now begin the "real" initialization.
// Corner case: List is empty.
if (futures.isEmpty()) {
set(combiner.combine(ImmutableList.<Optional<V>>of()));
return;
}
// Populate the results list with null initially.
for (int i = 0; i < futures.size(); ++i) {
values.add(null);
}
// Register a listener on each Future in the list to update
// the state of this future.
// Note that if all the futures on the list are done prior to completing
// this loop, the last call to addListener() will callback to
// setOneValue(), transitively call our cleanup listener, and set
// this.futures to null.
// This is not actually a problem, since the foreach only needs
// this.futures to be non-null at the beginning of the loop.
int i = 0;
for (final ListenableFuture<? extends V> listenable : futures) {
final int index = i++;
listenable.addListener(new Runnable() {
@Override
public void run() {
setOneValue(index, listenable);
}
}, listenerExecutor);
}
}
/**
* Sets the value at the given index to that of the given future.
*/
private void setOneValue(int index, Future<? extends V> future) {
List<Optional<V>> localValues = values;
if (isDone() || localValues == null) {
// Some other future failed or has been cancelled, causing this one to
// also be cancelled or have an exception set. This should only happen
// if allMustSucceed is true.
checkState(allMustSucceed,
"Future was done before all dependencies completed");
return;
}
try {
checkState(future.isDone(),
"Tried to set value from future which is not done");
localValues.set(index,
Optional.fromNullable(getUninterruptibly(future)));
} catch (CancellationException e) {
if (allMustSucceed) {
// Set ourselves as cancelled. Let the input futures keep running
// as some of them may be used elsewhere.
// (Currently we don't override interruptTask, so
// mayInterruptIfRunning==false isn't technically necessary.)
cancel(false);
}
} catch (ExecutionException e) {
if (allMustSucceed) {
// As soon as the first one fails, throw the exception up.
// The result of all other inputs is then ignored.
setException(e.getCause());
}
} catch (RuntimeException e) {
if (allMustSucceed) {
setException(e);
}
} catch (Error e) {
// Propagate errors up ASAP - our superclass will rethrow the error
setException(e);
} finally {
int newRemaining = remaining.decrementAndGet();
checkState(newRemaining >= 0, "Less than 0 remaining futures");
if (newRemaining == 0) {
FutureCombiner<V, C> localCombiner = combiner;
if (localCombiner != null) {
set(localCombiner.combine(localValues));
} else {
checkState(isDone());
}
}
}
}
}
/** Used for {@link #allAsList} and {@link #successfulAsList}. */
private static <V> ListenableFuture<List<V>> listFuture(
ImmutableList<ListenableFuture<? extends V>> futures,
boolean allMustSucceed, Executor listenerExecutor) {
return new CombinedFuture<V, List<V>>(
futures, allMustSucceed, listenerExecutor,
new FutureCombiner<V, List<V>>() {
@Override
public List<V> combine(List<Optional<V>> values) {
List<V> result = Lists.newArrayList();
for (Optional<V> element : values) {
result.add(element != null ? element.orNull() : null);
}
// TODO(user): This should ultimately return an unmodifiableList
return result;
}
});
}
/**
* A checked future that uses a function to map from exceptions to the
* appropriate checked type.
*/
private static class MappingCheckedFuture<V, X extends Exception> extends
AbstractCheckedFuture<V, X> {
final Function<Exception, X> mapper;
MappingCheckedFuture(ListenableFuture<V> delegate,
Function<Exception, X> mapper) {
super(delegate);
this.mapper = checkNotNull(mapper);
}
@Override
protected X mapException(Exception e) {
return mapper.apply(e);
}
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import javax.annotation.Nullable;
/**
* A {@link ListenableFuture} whose result may be set by a {@link #set(Object)}
* or {@link #setException(Throwable)} call. It may also be cancelled.
*
* @author Sven Mawson
* @since 9.0 (in 1.0 as {@code ValueFuture})
*/
public final class SettableFuture<V> extends AbstractFuture<V> {
/**
* Creates a new {@code SettableFuture} in the default state.
*/
public static <V> SettableFuture<V> create() {
return new SettableFuture<V>();
}
/**
* Explicit private constructor, use the {@link #create} factory method to
* create instances of {@code SettableFuture}.
*/
private SettableFuture() {}
/**
* Sets the value of this future. This method will return {@code true} if
* the value was successfully set, or {@code false} if the future has already
* been set or cancelled.
*
* @param value the value the future should hold.
* @return true if the value was successfully set.
*/
@Override
public boolean set(@Nullable V value) {
return super.set(value);
}
/**
* Sets the future to having failed with the given exception. This exception
* will be wrapped in an {@code ExecutionException} and thrown from the {@code
* get} methods. This method will return {@code true} if the exception was
* successfully set, or {@code false} if the future has already been set or
* cancelled.
*
* @param throwable the exception the future should hold.
* @return true if the exception was successfully set.
*/
@Override
public boolean setException(Throwable throwable) {
return super.setException(throwable);
}
}
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.base.Preconditions;
import com.google.common.collect.ForwardingObject;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* A {@link Future} which forwards all its method calls to another future.
* Subclasses should override one or more methods to modify the behavior of
* the backing future as desired per the <a
* href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>.
*
* <p>Most subclasses can just use {@link SimpleForwardingFuture}.
*
* @author Sven Mawson
* @since 1.0
*/
public abstract class ForwardingFuture<V> extends ForwardingObject
implements Future<V> {
/** Constructor for use by subclasses. */
protected ForwardingFuture() {}
@Override protected abstract Future<V> delegate();
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return delegate().cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return delegate().isCancelled();
}
@Override
public boolean isDone() {
return delegate().isDone();
}
@Override
public V get() throws InterruptedException, ExecutionException {
return delegate().get();
}
@Override
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return delegate().get(timeout, unit);
}
/*
* TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and
* constructor
*/
/**
* A simplified version of {@link ForwardingFuture} where subclasses
* can pass in an already constructed {@link Future} as the delegate.
*
* @since 9.0
*/
public abstract static class SimpleForwardingFuture<V>
extends ForwardingFuture<V> {
private final Future<V> delegate;
protected SimpleForwardingFuture(Future<V> delegate) {
this.delegate = Preconditions.checkNotNull(delegate);
}
@Override
protected final Future<V> delegate() {
return delegate;
}
}
}
| Java |
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Concurrency utilities.
*
* <p>Commonly used types include {@link
* com.google.common.util.concurrent.ListenableFuture} and {@link
* com.google.common.util.concurrent.Service}.
*
* <p>Commonly used utilities include {@link
* com.google.common.util.concurrent.Futures}, {@link
* com.google.common.util.concurrent.MoreExecutors}, and {@link
* com.google.common.util.concurrent.ThreadFactoryBuilder}.
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.util.concurrent;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.util.concurrent;
import com.google.common.annotations.Beta;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
/**
* An object with an operational state, plus asynchronous {@link #start()} and {@link #stop()}
* lifecycle methods to transition between states. Example services include webservers, RPC servers
* and timers.
*
* <p>The normal lifecycle of a service is:
* <ul>
* <li>{@linkplain State#NEW NEW} ->
* <li>{@linkplain State#STARTING STARTING} ->
* <li>{@linkplain State#RUNNING RUNNING} ->
* <li>{@linkplain State#STOPPING STOPPING} ->
* <li>{@linkplain State#TERMINATED TERMINATED}
* </ul>
*
* <p>There are deviations from this if there are failures or if {@link Service#stop} is called
* before the {@link Service} reaches the {@linkplain State#RUNNING RUNNING} state. The set of legal
* transitions form a <a href="http://en.wikipedia.org/wiki/Directed_acyclic_graph">DAG</a>,
* therefore every method of the listener will be called at most once. N.B. The {@link State#FAILED}
* and {@link State#TERMINATED} states are terminal states, once a service enters either of these
* states it cannot ever leave them.
*
* <p>Implementors of this interface are strongly encouraged to extend one of the abstract classes
* in this package which implement this interface and make the threading and state management
* easier.
*
* @author Jesse Wilson
* @author Luke Sandberg
* @since 9.0 (in 1.0 as {@code com.google.common.base.Service})
*/
@Beta
public interface Service {
/**
* If the service state is {@link State#NEW}, this initiates service startup and returns
* immediately. If the service has already been started, this method returns immediately without
* taking action. A stopped service may not be restarted.
*
* @return a future for the startup result, regardless of whether this call initiated startup.
* Calling {@link ListenableFuture#get} will block until the service has finished
* starting, and returns one of {@link State#RUNNING}, {@link State#STOPPING} or
* {@link State#TERMINATED}. If the service fails to start, {@link ListenableFuture#get}
* will throw an {@link ExecutionException}, and the service's state will be
* {@link State#FAILED}. If it has already finished starting, {@link ListenableFuture#get}
* returns immediately. Cancelling this future has no effect on the service.
*/
ListenableFuture<State> start();
/**
* Initiates service startup (if necessary), returning once the service has finished starting.
* Unlike calling {@code start().get()}, this method throws no checked exceptions, and it cannot
* be {@linkplain Thread#interrupt interrupted}.
*
* @throws UncheckedExecutionException if startup failed
* @return the state of the service when startup finished.
*/
State startAndWait();
/**
* Returns {@code true} if this service is {@linkplain State#RUNNING running}.
*/
boolean isRunning();
/**
* Returns the lifecycle state of the service.
*/
State state();
/**
* If the service is {@linkplain State#STARTING starting} or {@linkplain State#RUNNING running},
* this initiates service shutdown and returns immediately. If the service is
* {@linkplain State#NEW new}, it is {@linkplain State#TERMINATED terminated} without having been
* started nor stopped. If the service has already been stopped, this method returns immediately
* without taking action.
*
* @return a future for the shutdown result, regardless of whether this call initiated shutdown.
* Calling {@link ListenableFuture#get} will block until the service has finished shutting
* down, and either returns {@link State#TERMINATED} or throws an
* {@link ExecutionException}. If it has already finished stopping,
* {@link ListenableFuture#get} returns immediately. Cancelling this future has no effect
* on the service.
*/
ListenableFuture<State> stop();
/**
* Initiates service shutdown (if necessary), returning once the service has finished stopping. If
* this is {@link State#STARTING}, startup will be cancelled. If this is {@link State#NEW}, it is
* {@link State#TERMINATED terminated} without having been started nor stopped. Unlike calling
* {@code stop().get()}, this method throws no checked exceptions.
*
* @throws UncheckedExecutionException if the service has failed or fails during shutdown
* @return the state of the service when shutdown finished.
*/
State stopAndWait();
/**
* Registers a {@link Listener} to be {@linkplain Executor#execute executed} on the given
* executor. The listener will have the corresponding transition method called whenever the
* service changes state. The listener will not have previous state changes replayed, so it is
* suggested that listeners are added before the service starts.
*
* <p>There is no guaranteed ordering of execution of listeners, but any listener added through
* this method is guaranteed to be called whenever there is a state change.
*
* <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown
* during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception
* thrown by {@linkplain MoreExecutors#sameThreadExecutor inline execution}) will be caught and
* logged.
*
* @param listener the listener to run when the service changes state is complete
* @param executor the executor in which the the listeners callback methods will be run. For fast,
* lightweight listeners that would be safe to execute in any thread, consider
* {@link MoreExecutors#sameThreadExecutor}.
* @since 13.0
*/
void addListener(Listener listener, Executor executor);
/**
* The lifecycle states of a service.
*
* @since 9.0 (in 1.0 as {@code com.google.common.base.Service.State})
*/
@Beta // should come out of Beta when Service does
enum State {
/**
* A service in this state is inactive. It does minimal work and consumes
* minimal resources.
*/
NEW,
/**
* A service in this state is transitioning to {@link #RUNNING}.
*/
STARTING,
/**
* A service in this state is operational.
*/
RUNNING,
/**
* A service in this state is transitioning to {@link #TERMINATED}.
*/
STOPPING,
/**
* A service in this state has completed execution normally. It does minimal work and consumes
* minimal resources.
*/
TERMINATED,
/**
* A service in this state has encountered a problem and may not be operational. It cannot be
* started nor stopped.
*/
FAILED
}
/**
* A listener for the various state changes that a {@link Service} goes through in its lifecycle.
*
* @author Luke Sandberg
* @since 13.0
*/
@Beta // should come out of Beta when Service does
interface Listener {
/**
* Called when the service transitions from {@linkplain State#NEW NEW} to
* {@linkplain State#STARTING STARTING}. This occurs when {@link Service#start} or
* {@link Service#startAndWait} is called the first time.
*/
void starting();
/**
* Called when the service transitions from {@linkplain State#STARTING STARTING} to
* {@linkplain State#RUNNING RUNNING}. This occurs when a service has successfully started.
*/
void running();
/**
* Called when the service transitions to the {@linkplain State#STOPPING STOPPING} state. The
* only valid values for {@code from} are {@linkplain State#STARTING STARTING} or
* {@linkplain State#RUNNING RUNNING}. This occurs when {@link Service#stop} is called.
*
* @param from The previous state that is being transitioned from.
*/
void stopping(State from);
/**
* Called when the service transitions to the {@linkplain State#TERMINATED TERMINATED} state.
* The {@linkplain State#TERMINATED TERMINATED} state is a terminal state in the transition
* diagram. Therefore, if this method is called, no other methods will be called on the
* {@link Listener}.
*
* @param from The previous state that is being transitioned from. The only valid values for
* this are {@linkplain State#NEW NEW}, {@linkplain State#RUNNING RUNNING} or
* {@linkplain State#STOPPING STOPPING}.
*/
void terminated(State from);
/**
* Called when the service transitions to the {@linkplain State#FAILED FAILED} state. The
* {@linkplain State#FAILED FAILED} state is a terminal state in the transition diagram.
* Therefore, if this method is called, no other methods will be called on the {@link Listener}.
*
* @param from The previous state that is being transitioned from. Failure can occur in any
* state with the exception of {@linkplain State#NEW NEW} or
* {@linkplain State#TERMINATED TERMINATED}.
* @param failure The exception that caused the failure.
*/
void failed(State from, Throwable failure);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.